Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwable method overriding in Java

Tags:

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...");
    }
}
like image 675
Johnny Pepperoni Avatar asked Dec 18 '22 16:12

Johnny Pepperoni


2 Answers

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.

like image 174
Tom Hawtin - tackline Avatar answered Mar 01 '23 14:03

Tom Hawtin - tackline


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()
like image 31
ernest_k Avatar answered Mar 01 '23 16:03

ernest_k