Granular vs General Exception Handling
You'll learn: How to balance catching specific exceptions individually versus using broader catch blocks, and when each approach is appropriate.
The Design Trade-Off
When handling exceptions, you face a fundamental choice: should you catch each specific exception type separately (granular), or use a more general exception type that covers multiple cases (general)? Both approaches have distinct advantages and costs.
Granular handling means catching specific exception types with targeted responses:
try {
String data = readFile("data.txt");
int value = Integer.parseInt(data);
} catch (FileNotFoundException e) {
System.out.println("File not found, using default values");
// specific recovery action
} catch (NumberFormatException e) {
System.out.println("Invalid number format, aborting");
// different recovery action
} catch (IOException e) {
System.out.println("I/O error occurred");
// yet another specific action
}
General handling uses broader exception types:
try {
String data = readFile("data.txt");
int value = Integer.parseInt(data);
} catch (Exception e) {
System.out.println("Something went wrong: " + e.getMessage());
// one generic response
}
When to Use Each Approach
Prefer granular handling when:
- Different exceptions require different recovery strategies
- You need precise error reporting for debugging or user feedback
- Business logic demands specific responses to specific failures
Consider general handling when:
- All exceptions warrant the same response (e.g., logging and aborting)
- You're at a high level where specifics don't matter
- Rapid prototyping where detailed handling will come later
Key Takeaway: Granular exception handling provides precision and targeted recovery at the cost of verbosity, while general handling offers simplicity but loses context—choose based on whether your recovery logic differs by exception type.