简体   繁体   中英

Throwable method overriding in Java

First, sorry for my bad english. Question: If I have a subclass that extends a method which throws a CHECKED Exception, why Java's allow's me to throw a RuntimeException in the subclass's overriding method like the example below:

public class A {

    public void doSomething() throws FileNotFoundException {
        System.out.println("doing something...");
    }
}

And then...

public class B extends A {
    public void doSomething() throws RuntimeException { // <- my question
            System.out.println("doing something here too...");
    }
}

Any method can throw RuntimeException or Error - the unchecked exceptions base classes. So the throws RuntimeException is irrelevant to anything else.

You can override a method with a narrower throws clause. The throws FileNotFoundException does not imply the method must throw the exception. The method in the base class may throw it; the method in the derived method does not in this case.

You can't widen the throws clause because client code with a reference to the base class would not be expecting it.

This is similar to covariant return types where you can narrow the return type of method in a derived class/interface.

The whole idea about these restrictions is that a subclass should not force callers to catch another type of checked exception than the one(s) specified by the overridden method declaration (be it a broader one or a completely unrelated one).

In your case:

  • throws FileNotFoundException is completely omitted in B.doSomething : this is fine (it would also be fine if the subclass's method declared to throw a subclass of FileNotFoundException ). There would be a problem if B.doSomething() declared throws IOException or something completely unrelated, like throws SqlException .
  • throws RuntimeException is declaring that it can throw an unchecked exception. Callers are not forced to catch unchecked exceptions anyway, so this wouldn't break any code written to call A.doSomething()

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