简体   繁体   中英

Polymorphism and checked exception throwing in abstract methods

Suppose we have a class Foo with one method that may throw an IOException .

public abstract class Foo {
    public abstract void foo() throws IOException;
}

However, when I extend that class as FooImpl like so:

public class FooImpl extends Foo {
    public void foo() throws Exception {
        throw new Exception("This cannot throw!");
    }
}

This results in a compile time error: "Overwritten method does not throw java.lang.Exception"

I understand this is because the overriding method "may only throw checked exceptions of it's parent method, and any unchecked exceptions"

Why is this the case though? Why should we prohibit ourselves from throwing a broader exception?

(I'm also looking for a workaround)

Thanks!

You must always be able to use a subclass anywhere its superclass is used. That's pretty much literally the definition of a subclass, and more generally referred to as the Liskov substitution principle .

So the following must work, given that definition of Foo :

Foo foo = getFooFromSomewhere();
try {
  foo.foo();
} catch (IOException e) {
  // handle e
}

...since that matches the definition of Foo .

For this definition of FooImpl , that would not work, because Exception s that are not IOException are not handled, and as checked exceptions they must be caught or otherwise handled.

It's because of the contract that's established by the superclass. In other words, when the compiler "validates" an overridden method, it guarantees that programming against the API of the supertype will be possible using an instance of the subclass.

Practically, if you had

Foo foo = some foo implementation;
try {
    foo.foo();
} catch(IOException ioe) {
    //handle IOException
}

This catch block should be sufficient to handle the checked exception of the Foo API. But, if the compiler let subclasses raise checked exceptions other than the ones declared by the superclass, like Exception , then programming against Foo and handling all declared checked exceptions would be insufficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM