Multi-Catch Syntax (Java 7+)
What you'll learn: How to handle multiple exception types in a single catch block using Java 7's pipe operator.
The Problem with Repetitive catch Blocks
Before Java 7, if you wanted identical handling for multiple exception types, you had to write separate catch blocks with duplicate code. For example, catching both IOException and SQLException with the same logging logic meant writing nearly identical blocks.
The Multi-Catch Solution
Java 7 introduced multi-catch syntax, allowing you to catch multiple exception types in one catch block using the pipe operator (|):
try {
// code that may throw exceptions
} catch (IOException | SQLException e) {
System.out.println("Database or file error: " + e.getMessage());
}
This is cleaner and more maintainable than:
try {
// code that may throw exceptions
} catch (IOException e) {
System.out.println("Database or file error: " + e.getMessage());
} catch (SQLException e) {
System.out.println("Database or file error: " + e.getMessage());
}
Rules and Restrictions
- Separate with pipes: Use
|between exception types, not commas - Order doesn't matter: Unlike multiple
catchblocks, the order of types in a multi-catch doesn't affect compilation - No inheritance relationships: You cannot list a parent and child exception together (e.g.,
Exception | IOExceptioncauses a compiler error becauseIOExceptionis already covered byException)
When to Use Multi-Catch
Use multi-catch when different exception types require identical handling. If exceptions need different responses, use separate catch blocks.
Key Takeaway: Multi-catch syntax (catch (TypeA | TypeB e)) eliminates duplicate exception handling code by letting you catch multiple unrelated exception types in a single block.