Catching Sibling Exception Types
What you'll learn: How to handle multiple exception types that don't have a parent-child relationship in the same try-catch structure.
The Sibling Exception Scenario
So far, you've seen how to order catch blocks from most specific to most general when dealing with exception hierarchies (like catching FileNotFoundException before IOException). But what about exceptions that aren't related through inheritance? These are called sibling exceptions—they share a common ancestor (like Exception) but neither is a subclass of the other.
Understanding Sibling Relationships
Consider IOException and SQLException. Both extend Exception, but neither extends the other. They're siblings in the exception family tree. When your code might throw both types, you need separate catch blocks for each.
Order Doesn't Matter for Siblings
Here's the key difference: when exceptions are siblings, catch block order is flexible. The compiler doesn't enforce a specific sequence because neither block can make the other unreachable.
try {
// Code that might throw IOException or SQLException
} catch (IOException e) {
System.out.println("I/O problem: " + e.getMessage());
} catch (SQLException e) {
System.out.println("Database problem: " + e.getMessage());
}
You could reverse those catch blocks and the code would compile and behave identically. The JVM simply matches the thrown exception to the first compatible catch block it encounters.
Why This Matters
Understanding sibling exceptions helps you recognize when order flexibility exists versus when it's strictly enforced (parent-child relationships). This becomes important when refactoring or adding new exception handlers to existing code.
Key Takeaway: Sibling exception types (unrelated by inheritance) can be caught in any order because neither catch block can overshadow the other; each handles a distinct exception type that the other cannot match.