When a block of code has the potential to throw more than one type of exception, Java provides two main strategies: Multiple Catch Blocks and the Multi-Catch (Pipe) Syntax. These techniques allow you to define specific recovery paths for different errors while keeping your codebase DRY (Don't Repeat Yourself).
Before Java 7, if you wanted to handle different exceptions differently, you had to stack catch blocks one after another. The JVM checks these blocks from top to bottom.
Exception (the parent) first, the blocks for ArithmeticException (the child) will never be reached, causing a compiler error.
Introduced in Java 7, the Multi-Catch feature allows you to catch several unrelated exceptions in a single catch block using the vertical bar or pipe symbol (|). This is perfect when the recovery logic is the same for multiple errors.
Constraints of Multi-Catch: You cannot catch two exceptions in a single pipe if they have a Parent-Child relationship (e.g., catch (IOException | FileNotFoundException e) is illegal because IOException already covers its child).
To write robust code, developers often use specific catches for known issues and a final "Catch-All" block for unexpected failures.
| Catch Order | Exception Type | Purpose |
|---|---|---|
| 1st (Specific) | FileNotFoundException |
Handle missing files specifically (e.g., ask user for new path). |
| 2nd (Mid-level) | IOException |
Handle general I/O issues (e.g., network timeout). |
| 3rd (General) | Exception |
The safety net for any other runtime errors. |
This code simulates a scenario where we read an array and perform division—two operations that can fail in very different ways.
Sometimes you want to catch an exception, log it, and then "pass it up" to the calling method. You do this by using the throw keyword inside the catch block.
catch (IOException e) {
logger.log(e);
throw e; // Rethrowing to the caller
}
TimeoutException (by retrying) while failing fast on a SecurityException.Q: Why does the compiler complain if I catch 'Exception' before 'NullPointerException'?
A: Because Exception is the parent. Since it can catch anything, the NullPointerException block becomes "Unreachable Code," which Java does not allow.
Q: In a Multi-catch block (pipe syntax), what is the type of the exception variable?
A: The variable (e.g., e) is implicitly final. You cannot reassign it within the catch block.
Q: Can we use a single catch for both Error and Exception?
A: Yes, by catching Throwable, but this is highly discouraged as Errors are typically unrecoverable system failures.
Handling multiple exceptions is a sign of a mature developer. By ordering your catch blocks from specific to general and utilizing the modern pipe syntax, you create code that is both resilient to failure and easy for other developers to maintain. Always remember: Catch what you can handle, and throw what you can't.
Next: Creating Custom Exceptions →