W3docs

Can I catch multiple Java exceptions in the same catch clause?

Yes, you can catch multiple exceptions in the same catch clause in Java.

Yes, you can catch multiple exceptions in the same catch clause in Java.

To catch multiple exceptions in the same catch clause, you can specify a list of exceptions separated by a vertical bar (|). This feature requires Java 7 or higher.

For example:


try {
    // code that may throw exceptions
} catch (IOException | SQLException | ArithmeticException e) {
    // handle exceptions
}

This will catch any IOException, SQLException, or ArithmeticException thrown by the code in the try block, and execute the same exception handling code for all of them. Note that the catch parameter (e) is implicitly final and cannot be reassigned.

The catch clause will be executed only if the exception thrown by the try block is one of the specified types, or a subtype of one of the specified types.

If you need to handle each exception differently, you must use separate catch clauses. Note that Java does not allow multiple catch clauses for the same exception type, as the compiler will report a duplicate catch block error.

For example:


try {
    // code that may throw exceptions
} catch (IOException e) {
    // handle IOException
} catch (SQLException e) {
    // handle SQLException
} catch (ArithmeticException e) {
    // handle ArithmeticException
}

In this case, each catch clause handles a specific exception type, and the corresponding handling code executes only for that type.