Throwable method overriding in Java

Johnny Pepperoni :

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...");
    }
}
Tom Hawtin - tackline :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=121492&siteId=1