In Java, multiple catch blocks allow you to handle different types of exceptions separately within a single try block. This improves error handling clarity and prevents application crashes.
try blockcatchJava allows more than one catch block after a single try. The JVM matches the thrown exception with the first compatible catch block.
// Syntax of multiple catch blocks in Java
try {
// code that may throw exceptions
} catch (ExceptionType1 e) {
// handle exception type 1
} catch (ExceptionType2 e) {
// handle exception type 2
}
// Demonstrating multiple catch blocks
public class MultipleCatchDemo {
public static void main(String[] args) {
try {
int[] numbers = {10, 20, 30};
System.out.println(numbers[5]);
int result = 10 / 0;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error occurred");
} catch (ArithmeticException e) {
System.out.println("Arithmetic error occurred");
}
}
}
Array index error occurred
The program throws an ArrayIndexOutOfBoundsException first, so the corresponding catch block executes. Remaining code is skipped.
The array is {10, 20, 30} (Valid indexes: 0, 1, 2).
Change values to see which block catches the error!
Exception as a catch-allNullPointerException catch block