Java multiple catch blocks

A try block could be followed by one or more catch blocks. Each catch block is meant for handling specific exception. If we would like to handle all possible exceptions in the same way then we could go for only one catch block by catching Exception/Throwable.

At a time, only one exception occurs in a try block and only one catch block executes.

Example 01 – try with multiple catch blocks

Output :

main begin
ArithmeticException raised
main end

In the above example, one try block is followed by multiple catch blocks. Here each catch block is used to deal with one specific exception.

Example 02 – try with multiple catch blocks – catch unknown exception

Output :

main begin
Unknown Exception raised
java.lang.NullPointerException: Cannot store to int array because “a” is null
main end

In the above example, we don’t have catch block to deal with NullPointerException. In general we will define last catch block to catch any kind of exception to deal with unknown exception.

Example 03 – try with multiple catch blocks – catch blocks order

Compilation Error : Unreachable catch block for XXXException. It is already handled by the catch block for Exception

In the above example, catch blocks are defined in order from generic to specific exception. It leads to Compilation error. So catch blocks order should always defined from specific to general exception(subclass to super class exception).

Example 04 – try with multiple catch blocks – one catch block catches multiple exceptions

Output :

main begin
ArithmeticException | ArrayIndexOutOfBoundsException handles in same way
main end

If we would like to handle couple of exceptions in same way then we could catch them in one catch block with ‘|’ operator between them. This feature is available from Java 1.7 version onwards.

If a catch block handles more than one exception type, then the catch parameter is implicitly final

Scroll to Top