Can a method in a subclass override a method in the parent class and throw a run time exception when the method in the parent class throws no exception? Something like this:
class X { public void foo() { System.out.print("X "); } }
public class SubB extends X {
public void foo() throws RuntimeException {
super.foo();
if (true)
throw new RuntimeException();
System.out.print("B ");
}
public static void main(String[] args) {
new SubB().foo();
}
}
Yes, because runtime exceptions aren’t part of the method signature. (You can add them but the compiler doesn’t care, they’re just documentation.)
I think the rationale is that RuntimeExceptions are usually programmer errors, like NPEs or going out of bounds of an array, so it doesn’t make sense to try to restrict them the way that checked exceptions are restricted. You can’t make a rule saying, this method (and any method overriding it) can never ever throw a NullPointerException, because the JVM doesn’t make those kinds of guarantees.
In the Java Language Specification under Compile-Time Checking of Exceptions it says: