Course contentsShow
← Java
Lesson 792 of 2,87019. Exception Hierarchy and Custom ExceptionsFree lesson

Overriding Methods and Exception Compatibility

Learn that overriding methods can throw fewer or more specific checked exceptions but cannot introduce new broader checked exception types.

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 declare throws FileNotFoundException (more specific)
  • Parent declares throws IOException → Child can declare no exceptions (fewer)
  • Parent declares throws IOException → Child can declare throws IOException, NullPointerException (adding unchecked is fine)

What's NOT Allowed

  • Parent declares throws IOException → Child cannot declare throws Exception (broader)
  • Parent declares throws FileNotFoundException → Child cannot declare throws 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.