Java Exceptions – How JVM Handles Exceptions Thrown by Main Method

exceptionsjavajvm

I understand exceptions, throwing them, handling them, and propagating them to a method lower in the call stack (i.e. throws).

What I don't understand is this:

public static void main(String[] args) throws Exception {
    ...
}

Now, I assume that in the case that main throws an Exception, the JVM handles it (correct?). If that's the case, then my question is:

How does the JVM handle exceptions thrown by main? What does it do?

Best Answer

You might think that the public static void main method in Java or the main function in C is the real entry point of your program – but it isn't. All high-level languages (including C) have a language runtime that initializes the program, and then transfers control flow to the entry point. In the case of Java, initialization will include:

  • setting up the JVM
  • loading required classes
  • running static initializer blocks. This can execute user-defined code before main is invoked. These blocks aren't supposed to throw exceptions.

There are a variety of ways to implement exception handling, but for the purpose of this question, they all can be viewed as a black box. The important thing however is that the language runtime must always provide an outermost exception handler that catches all exceptions that aren't caught by user code. This exception handler will usually print out a stack trace, shut down the program in an orderly fashion, and exit with an error code. Properly shutting down the program includes destroying the object graph, invoking finalizers, and freeing resources such as memory, file handles, or network connections.

For purposes of illustration, you can imaging the runtime wrapping all code in a giant try-catch that looks like

try {
    loadClasses();
    runInitializers();
    main(argv);
    System.exit(0);
} catch (Throwable e) {
    e.printStackTrace();
    System.exit(-1);
}

except that it's not necessary for a language to actually execute code like this. The same semantics can be implemented in the code for throw (or equivalent) that searches for the first applicable exception handler.

Related Topic