I have this snippet.
public final class StackOverflow{
class MyException extends Throwable{
}
private void a(){
try{
}catch(MyExceptio
It is explained in the Java Language Specification (emphasis in bold):
It is a compile-time error if a
catch
clause can catch checked exception class E1 and it is not the case that thetry
block corresponding to thecatch
clause can throw a checked exception class that is a subclass or superclass of E1, unless E1 isException
or a superclass ofException
.
I guess the rationale behind this is that: MyException
is indeed a checked exception. However, unchecked exceptions also extend Exception
(transitive inheritance from RuntimeException
), so having a catch
include the Exception
class is excluded from the exception analysis done by the compiler.
Exception extends from RuntimeException
will considered as uncheched exception, so it's ok:
class MyException extends RuntimeException { }
try {
...
} catch (MyException e) {
}
Your exception extends from Throwable
, so it is cheched exception. Since the compiler noticed that it is never thrown, so the compile fails.