Java - Multi-Catch Block

What is Multi-Catch Block

Java has support for a multi-catch block to handle multiple types of exceptions in a catch block.

Syntax

The following code wants to catch three exceptions: Exception1, Exception2, and Exception3.

The code would look as follows:

try {
        // Code that may throw Exception1, Exception2, or Exception3
}
catch (Exception1 e1){
        // Handle Exception1
}
catch (Exception2 e2){
        // Handle Exception2
}
catch (Exception3 e3){
        // Handle Exception3
}

The above code can be written as follows:

try {
        // May throw Exception1, Exception2, or Exception3
}
catch (Exception1 | Exception2 | Exception3  e) {
        // Handle Exception1, Exception2, and Exception3
}

Rule

In a multi-catch block, you cannot have alternative exceptions that are related by subclassing.

For example, the following multi-catch block is not allowed, because Exception1 and Exception2 are subclasses of Throwable:

try {
    // May throw Exception1, Exception2, or Exception3
}
catch (Exception1 | Exception2 | Throwable  e) {
        // Handle Exceptions here
}

Related Topics