From javaDocs on java.lang.Exception
class:
Checked exceptions need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.
But consider this code:
package other;
public class CheckedExceptionHandling {
private static <E extends Exception> void throwException() throws E {
throw (E) new CheckedException2(); // unchecked cast warning
}
private static void setUncaughtExceptionHandler() {
Thread.currentThread().setUncaughtExceptionHandler((t, e) -> {
System.out.println("Unhandled exception: " + e.getClass()); // reports CheckedExceptionHandling$CheckedException2
});
}
public static void main(String[] args) /* no checked exceptions declared! */ {
setUncaughtExceptionHandler();
try {
CheckedExceptionHandling.<CheckedException1>throwException();
} catch (CheckedException1 e) {
System.out.println(e); // never gets here
}
}
// checked exceptions:
public static class CheckedException1 extends Exception {}
public static class CheckedException2 extends Exception {}
}
It compiles with a warning and the run-time result is:
Unhandled exception: class other.CheckedExceptionHandling$CheckedException2
I expected a compile-time error unreported exception CheckedException2; must be caught or declared to be thrown
or incompatible types: CheckedException2 cannot be converted to CheckedException1
or at least a ClassCastException
at run time.
But the compiler allows a checked exception to be left unhandled, undeclared and propagate outside the method main
to the uncaught exception handler.
Why? Am I missing something here?