Multiple Catch Blocks

Handling Multiple Exceptions:

  • 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.
Code Example
Output
Array index is out of bounds.

Explanation:

  • The program encounters an ArrayIndexOutOfBoundsException, which is caught by the first catch block. The second catch block is not executed because the exception is already handled.