Overriding Methods and Exception Compatibility
What You'll Learn
You'll learn the rules Java enforces when an overriding method declares exceptions—specifically how it can narrow, but never broaden, the checked exceptions thrown.
The Core Rule
When you override a method, you're creating a contract that must be compatible with the parent class's contract. For exceptions, this means:
- Checked exceptions: You can declare the same checked exception, a more specific (subclass) checked exception, fewer checked exceptions, or none at all—but you cannot introduce new, broader, or different checked exceptions.
- Unchecked exceptions: You have complete freedom. You can declare any unchecked exceptions (or none) regardless of what the parent method declares.
Why This Rule Exists
Think of method overriding as making a promise to code that uses the parent class reference. If Parent.method() declares throws IOException, calling code knows to handle that specific exception. If a subclass could override the method and throw SQLException instead, the calling code would break—it wasn't prepared for that exception type.
By restricting overriding methods to more specific or fewer checked exceptions, Java ensures that polymorphism remains safe: any code that works with the parent type will also work correctly with subclass instances.
Examples of What's Allowed
- Parent declares
throws IOException→ Child can declarethrows FileNotFoundException(more specific) - Parent declares
throws IOException→ Child can declare no exceptions (fewer) - Parent declares
throws IOException→ Child can declarethrows IOException, NullPointerException(adding unchecked is fine)
What's NOT Allowed
- Parent declares
throws IOException→ Child cannot declarethrows Exception(broader) - Parent declares
throws FileNotFoundException→ Child cannot declarethrows SQLException(different checked type)
Key Takeaway: Overriding methods must maintain or narrow the exception contract for checked exceptions—never widen it—ensuring polymorphic code remains exception-safe.