Course contentsShow
← Java
Lesson 421 of 2,87010. Inheritance FundamentalsFree lesson

Checked Exceptions in Overriding Methods

Learn that overriding methods can declare fewer or narrower checked exceptions, but not broader ones.

Checked Exceptions in Overriding Methods

What you'll learn: You'll discover how overriding methods are restricted in which checked exceptions they can declare.

The Core Rule

When you override a method from a superclass, you cannot declare broader or additional checked exceptions in the subclass method—only narrower or fewer exceptions. This rule ensures that anyone holding a superclass reference can safely catch the exceptions they expect, without surprises from subclass implementations.

Why This Rule Exists

Imagine a FileReader class with a read() method that throws IOException. If a subclass SpecialFileReader could override read() to throw SQLException (a different checked exception), code expecting only IOException would break:

FileReader reader = new SpecialFileReader();
try {
    reader.read(); // Expects IOException, but might get SQLException!
} catch (IOException e) {
    // This won't catch SQLException!
}

Java prevents this at compile time.

What's Allowed

  • Declaring no exceptions (even if the superclass method declares some)
  • Declaring the same exception
  • Declaring a subclass of the superclass's exception (narrower)
  • Declaring fewer exceptions from the superclass's list

What's NOT Allowed

  • Declaring a superclass of the superclass's exception (broader)
  • Declaring completely different checked exceptions

The Analogy

Think of the superclass method as a "contract" promising "I might throw these problems." The subclass can say "I throw fewer problems" or "I throw smaller versions of those problems," but never "I throw bigger or different problems."

Key Takeaway:
Overriding methods can declare fewer or narrower checked exceptions than the superclass method, but never broader or additional ones—this maintains type safety for polymorphic calls.