Amol.Shaligram
Amol.Shaligram

Reputation: 793

Who prints exception stack trace in case of unhandled exceptions in java?

When using a try / catch block, we can print the stack trace in the catch block using the e.printStacktrace() method.

In case of an unhandled exception the stack trace still gets printed.

Who prints that stack trace on the console? and how?

Upvotes: 1

Views: 2091

Answers (1)

Michael Berry
Michael Berry

Reputation: 72254

If an exception isn't caught explicitly in Java (by a catch block) in the code that you're looking at, then the following will happen:

  • The exception will propagate up the call stack until it finds another catch block to handle it. If so, great. If it gets to the top of the stack and there's no catch block to handle it, then:

  • It's handled by whatever is specified as the uncaught exception handler for that thread. This is a block of code that's explicitly set to run if this scenario occurs. If no handler is specified, then:

  • It will call uncaughtException() on ThreadGroup. As per its Javadoc, this does the following:

    • If this thread group has a parent thread group, the uncaughtException method of that parent is called with the same two arguments.
    • Otherwise, this method checks to see if there is a default uncaught exception handler installed, and if so, its uncaughtException method is called with the same two arguments.
    • Otherwise, this method determines if the Throwable argument is an instance of ThreadDeath. If so, nothing special is done. Otherwise, a message containing the thread's name, as returned from the thread's getName method, and a stack backtrace, using the Throwable's printStackTrace method, is printed to the standard error stream.

The bolding is mine, and that's the behaviour that's responsible, by default, for printing your stack trace.

As an aside, you can actually verify that last part if you so wish - something like this will print a (short) stack trace, as you'd expect:

public static void main(String[] args) throws Throwable {
    throw new Throwable();
}

Exception in thread "main" java.lang.Throwable at javaapplication6.JavaApplication6.main(JavaApplication6.java:18)

Yet as per the above docs, this doesn't print anything:

public static void main(String[] args) throws Throwable {
    throw new ThreadDeath();
}

Upvotes: 4

Related Questions