The Need for Multiple catch Blocks
What you'll learn: Why catching just one exception type often isn't enough and when different exceptions demand different responses.
Beyond the Single Catch
By now you've seen how a catch block handles exceptions, but what if your try block can throw different types of exceptions? A single catch isn't always sufficient because different problems require different solutions.
Think of it like a first-aid kit: you wouldn't use the same treatment for a burn, a cut, and a bee sting. Similarly, different exceptions often need different handling strategies.
When One Size Doesn't Fit All
Consider code that opens a file and parses numbers from it. You might encounter:
- FileNotFoundException if the file doesn't exist → log an error, use default data
- NumberFormatException if the content isn't numeric → skip the invalid line, continue
- IOException for other read failures → abort, alert the user
Each scenario calls for a distinct response. Catching a generic Exception for all three would force you into clunky conditional logic or inappropriate uniform handling.
The Solution: Multiple Catch Blocks
Java lets you chain multiple catch blocks after a single try. Each catches a specific exception type:
try {
// code that may throw different exceptions
} catch (FileNotFoundException e) {
System.out.println("File not found, using defaults.");
} catch (NumberFormatException e) {
System.out.println("Invalid number format, skipping entry.");
} catch (IOException e) {
System.out.println("Read error: " + e.getMessage());
}
Java checks each catch in order from top to bottom, executing the first matching block. This gives you precise, tailored error handling for each failure scenario.
Key Takeaway: Multiple catch blocks let you respond appropriately to different exception types, treating each error condition with the specific logic it requires rather than forcing all failures through generic handling.