In this example, the 2nd catch block is unreachable and therefore my code does not compile. However, if I make LimpException
extend RuntimeException
instead of Exception
, it compiles without any trouble. Why?
public class Finals {
public void run() {
try {
spit();
} catch (HurtException e) {
System.out.println("");
} catch (LimpException ex) { // does not compile, unreachable code
System.out.println("");
}
}
public void spit() throws HurtException { // method that throws the Exception
}
public static void main(String... args) {
}
}
class LimpException extends Exception { // extends Exception vs extends
// RuntimeException
}
class HurtException extends LimpException {
}
According to the JLS §11.2:
The unchecked exception classes (§11.1.1) are exempted from compile-time checking.
That's pretty simple. Even though that code block is still unreachable, the compiler simply doesn't check.
In your example, LimpException
cannot be thrown from the try statement body that isn't already caught by the catch LimpException
catch block. This is banned by JLS §11.2.3:
It is a compile-time error if a catch clause can catch checked exception class E1 and it is not the case that the try block corresponding to the catch clause can throw a checked exception class that is a subclass or superclass of E1, unless E1 is Exception or a superclass of Exception.
It is a compile-time error if a catch clause can catch (§11.2) checked exception class E1 and a preceding catch clause of the immediately enclosing try statement can catch E1 or a superclass of E1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With