Can I catch multiple Java exceptions in the same catch clause?
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 (|
).
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.
Keep in mind that 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.
It is also possible to catch multiple exceptions of the same type by using multiple catch clauses with the same exception type. However, this is generally not recommended as it can lead to redundant and repetitive code.
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 will handle a different type of exception, and the exception handling code will be executed only for the specific type of exception that was thrown.