In Java, multiple catch blocks allow us to handle different types of exceptions separately. This is useful when a single try block contains code that may throw different types of exceptions.
A try block can be followed by one or more catch blocks, and each catch block must handle a different type of exception. This allows you to perform specific actions depending on the type of exception that occurs.
Alternatively, starting from Java 7, we can combine multiple exceptions in a single catch block using the | (pipe) symbol.
A multiple catch block is used when a try block can throw different types of exceptions. Each catch handles a specific exception, and more specific exceptions should come before general ones. From Java 7 onward, multiple exceptions can be handled in a single catch block using the | (pipe) symbol.
The following image shows the flowchart of the working of multiple catch blocks:

The syntax for using multiple catch blocks:
Here is the syntax to use multiple catch blocks together using the pipe (|) sign:
The following example demonstrates using multiple catch blocks:
Output:
Caught ArrayIndexOutOfBoundsException: Invalid array index accessed. Program continues after handling multiple exceptions.
Practice the following examples to understand how multiple catch blocks work in Java.
The following example demonstrates how an ArithmeticException is caught using multiple catch blocks.
Output:
Arithmetic Exception occurs rest of the code
The following example demonstrates how an ArrayIndexOutOfBoundsException is caught using multiple catch blocks.
Output:
ArrayIndexOutOfBounds Exception occurs rest of the code
In this example, the try block contains two exceptions. But at a time only one exception occurs and its corresponding catch block is executed.
In this example, the try block may throw multiple exceptions, but only the first occurring exception is handled.
Output:
Arithmetic Exception occurs rest of the code
If the exception does not match a specific catch block, the parent Exception catch block is executed.
Output:
Parent Exception occurs rest of the code
Placing a general exception catch block before specific ones causes a compile-time error.
Output:
Main.java:13: error: exception ArithmeticException has already been caught
catch(ArithmeticException e)
^
Main.java:17: error: exception ArrayIndexOutOfBoundsException has already been caught
catch(ArrayIndexOutOfBoundsException e)
We request you to subscribe our newsletter for upcoming updates.