You can have multiple catch
blocks to handle different types of exceptions. The most specific exceptions should be caught first, followed by more general exceptions.
NOTE:
If we use try with multiple catch blocks then the order of catch blocks is very important we have to take child first and then parent. Otherwise we will get compile time error saying.
Exception XXX has already been caught.
import java.io.*;
public class PlanetLearning {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException
int num1 = 10;
int num2 = 0;
int result = num1 / num2; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds.");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
}
}
Array index is out of bounds.
Explanation:
ArrayIndexOutOfBoundsException
, which is caught by the first catch
block. The second catch
block is not executed because the exception is already handled.