Home / Questions / Why do you need multiple catch handlers?
Explanatory Question

Why do you need multiple catch handlers?

👁 42 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

Sometimes, a single block of code may throw different types of exceptions.
In such cases, we can use multiple catch blocks with a single try block — each designed to handle a specific type of exception.

For example:


try {
    int a[] = new int[5];
    a[6] = 10; // This will cause ArrayIndexOutOfBoundsException
}
catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Array index out of range!");
}
catch (Exception e) {
    System.out.println("Some other exception occurred!");
}

This allows specific handling for different errors that might occur within the same try block.