Exception Handling in Java
Exception Handling in Java
Hey there! In this guide, we'll explore exception handling in Java. Exception handling helps manage runtime errors and prevents abrupt termination of programs, making applications more reliable and easier to debug.
Video Explanation

1. What is Exception Handling?
Exception handling is a mechanism used to handle runtime errors so that the normal execution of the program can continue.
Java uses the following keywords:
trycatchthrowthrowsfinally
2. The try Block
The try block contains code that may generate an exception.
Syntax:
try {
// risky code
}
Example:
try {
int x = 10 / 0;
}
3. The catch Block
The catch block handles exceptions generated inside the try block.
Syntax:
catch(ExceptionType e) {
// handling code
}
Example:
catch(ArithmeticException e) {
System.out.println(e);
}
4. Complete Example of Exception Handling
Example:
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(result);
}
catch(ArithmeticException e) {
System.out.println("Division by zero is not allowed");
}
}
}
Output:
Division by zero is not allowed
5. Multiple Catch Blocks
Java allows multiple catch blocks to handle different exception types.
Example:
public class Main {
public static void main(String[] args) {
try {
String str = null;
System.out.println(str.length());
}
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception");
}
catch(NullPointerException e) {
System.out.println("Null Pointer Exception");
}
}
}