The detailed flowchart of full uncaught exception handling is given here: How uncaught exceptions are handled in Java.
When an uncaught exception occurs, the JVM does the following:
- it calls a special private method,
dispatchUncaughtException()
, on the Thread
class in which the exception occurs;
- [...which] calls the thread's
getUncaughtExceptionHandler()
method to find out the appropriate uncaught exception handler to use. Normally, this will actually be the thread's parent ThreadGroup
, whose handleException()
method by default will print the stack trace.
- it then terminates the thread in which the exception occurred.
Therefore you can, if you wish to, create your own custom uncaught exception handler.
It should also be noted that while main
is commonly used as a Java application entry point, the method is just like any other methods in that it can also be called from other contexts (e.g. other main
methods, or even itself recursively!). In that case, the caller can catch exceptions thrown.
public class SelfCatch {
public static void main(String args[]) throws Exception {
if (args == null) throw new Exception("Hi there!");
try {
main(null);
} catch (Exception e) {
System.out.println("Caught: " + e);
}
System.out.println("Exiting...");
}
}
Output:
Caught: java.lang.Exception: Hi there!
Exiting...