LSP and Exception Handling
You'll learn: How throwing unexpected exceptions in subclasses violates the Liskov Substitution Principle by breaking your contract with client code.
The Core Idea
When a subclass overrides or implements a parent class method, it must honor the exception contract established by the parent. Specifically, you cannot throw new checked exceptions that the parent didn't declare. If you do, code that works with the parent type will unexpectedly break when given a subclass instance—violating LSP.
Think of it like a restaurant menu. If the menu says a dish is "nut-free," customers with allergies trust that promise. If the kitchen suddenly adds peanuts to one location's version without updating the menu, that's dangerous. Similarly, if a parent method declares it throws IOException, clients prepare for that. If a subclass suddenly throws SQLException (not declared by parent), the client can't handle it—the program crashes.
Why This Matters
Clients write code against abstractions (interfaces, base classes). They use try-catch blocks based on declared exceptions. If a subclass introduces new checked exceptions:
- Client code won't catch them (compile-time safety is bypassed)
- The subclass isn't truly substitutable for the parent
- You've broken the behavioral contract
The Rule
Subtypes can:
- Throw the same exceptions as the parent
- Throw subclasses of the parent's declared exceptions (more specific is fine)
- Throw fewer or no exceptions (more lenient is fine)
Subtypes cannot:
- Throw entirely new checked exception types not in the parent's hierarchy
Key Takeaway: Respect the exception contract—subtypes must not surprise callers with new checked exceptions beyond what the parent declared, ensuring true substitutability.