Why do you need multiple catch handlers?

Single Choice
Views 33

Answer:

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.

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.