"Handle or declare. That's the law." - Head First
But, is it a good law? Let me give an example first:
public static void main(String[] args) throws Exception {
m1();
}
static void m1() throws Exception{
m2();
}
static void m2() throws Exception {
throw new Exception();
}
m2()
throws exception and m1()
calls m2()
, meaning it must either handle or declare it. Hmmm let's declare it. Then main()
calls m1()
and it has same poll: declare or handle. I again decided to declare it and code compiles just fine.
Okay, it works, but who handled this exception at all? Looks like no one did. I know I am a beginner, but I don't like the sound of that. Yes, some methods can decide whether to declare or handle exceptions, but why main()
? Shouldn't main method be one that just handles? In that way, no exception could "slip".
Am I missing something to this? I was honestly surprised that it is okay for main method to just declare exception, knowing that it is the last place we could technically catch something.
The Java runtime did.
More specifically, the
UncaughtExceptionHandler
did, as specified in the Java Language Specification (JLS), section 11.3. Run-Time Handling of an Exception:So, by default, when
main()
throws an exception, unchecked or checked, the built-in default "uncaught exception handler" will simply print the stacktrace toSystem.err
, as-if the following was executed right beforemain()
was called:After the "uncaught exception handler" has been invoked the thread is terminated, same as if you simply return from the
main()
method, and unless the code has started non-daemon threads that are still running, the program ends.