Exception Handling in Java is a powerful mechanism that allows a program to handle runtime errors gracefully. Instead of crashing the program, Java provides structured ways to detect, catch, and respond to unexpected situations.
try, catch, finally, throw, and throwsThrowable hierarchyJava wraps risky code inside a try block and handles errors using one or more catch blocks. Optional cleanup code goes inside finally.
// Basic try-catch syntax in Java
try {
int a = 10;
int b = 0;
int result = a / b;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
Enter two numbers to simulate Java's ArithmeticException handling.
Try entering 0 as the second number!
// Handling an exception with finally block
try {
int[] nums = {1, 2, 3};
System.out.println(nums[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of range");
} finally {
System.out.println("Execution completed");
}
When an exception occurs, Java immediately transfers control to the matching catch block. The finally block always executes, whether an exception occurs or not.
finally for cleanup code like closing filesNullPointerException