Home / Questions / How does a try statement determine which catch clause should be used to handle an exception?
Explanatory Question

How does a try statement determine which catch clause should be used to handle an exception?

👁 31 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

When an exception is thrown within a try block, the catch clauses are checked in the order they appear.
The first catch block capable of handling the thrown exception is executed, and the remaining catch blocks are ignored.

Example:


try {
    int[] nums = new int[5];
    nums[10] = 50; // ArrayIndexOutOfBoundsException
}
catch (ArithmeticException e) {
    System.out.println("Arithmetic Exception caught.");
}
catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Array Index Out of Bounds Exception caught.");
}

Output:


Array Index Out of Bounds Exception caught.