Thumb rules for exceptions ("throws <some-exception>") in overridden methods

Viewed 37

I'm trying to come up with some simple rules to remember regarding exceptions in overridden methods in Java 8.

I've seen some posts explaining this in a kind of long way or not so clear to me.

Assume when saying "Checked exception" it means the method has throws <checked-exception> in its signature etc.

  1. Checked exceptions can stay the same or be narrowed, even to not throwing at all.
  2. Unchecked exceptions (runtime exceptions) have no rules (can be narrowed or widened or neither).

To keep the statement simple assume that narrowing "not throwing at all" is "not throwing at all" and widening "not throwing at all" is to throw any exception (corresponding to checked/unchecked case)

Summarizing this to:

  1. checked >= overriding-checked
  2. unchecked, overriding-unchecked are independent

Is this all (and correct?) or are there some cases missing?

1 Answers

You're correct.

Let's say we have classes

public class Parent {
    public void doit() throws IOException {
        throw new IOException();
    }
}

public class Child extends Parent {
    public void doit() throws FileNotFoundException {
         throw new FileNotFoundException();
    }
}

Checked exceptions are the ones that you're required to handle. If Child were to throw a checked exception that is not an IOException (FileNotFoundException is an IOException, so it's okay as written), that would mean that this code lets this checked exception roam free:

Parent object = new Child();
try {
    object.doit();
} catch (IOException ex) {
    // thoughtful and careful handling
}

This would create a situation when a method threw a checked exception that is not declared in its throws list and defeat the definition and purpose of checked exceptions. Therefore language designers prohibited this.

Related