Question
Can I catch multiple Java exceptions in the same catch clause?
try {
// Code that may throw exceptions
} catch (IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchFieldException e) {
someCode();
}
Answer
In Java, since version 7, you can catch multiple exceptions in a single catch block using the pipe (`|`) operator. This feature simplifies exception handling by reducing code redundancy and improving readability.
try {
// Code that may throw exceptions
} catch (IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchFieldException e) {
someCode(); // Handle all exceptions here
}
Causes
- This is commonly needed when multiple exceptions share the same handling logic.
- Catching exceptions individually can lead to repetitive code.
Solutions
- Use the pipe character `|` to combine multiple exception types in a single catch clause.
- Remember to catch exceptions from the same hierarchy when using multi-catch.
Common Mistakes
Mistake: Combining unrelated exceptions that require different handling.
Solution: Ensure that the exceptions can be logically handled in the same way before combining.
Mistake: Not catching specific exceptions while attempting multi-catch.
Solution: Make sure to include all exceptions that may be thrown within the try block.
Mistake: Forgetting that multi-catch can affect exception order in finally blocks.
Solution: Be aware of the catch order if further handling in a finally block is necessary.
Helpers
- Java catch multiple exceptions
- Java multi-catch block
- Java exception handling best practices
- Java try catch examples