Providing a default exception handling strategy in Java applications

Steve Neal Development, Java Programming 2 Comments

When writing a Java application you may need to consider how that application should react when an uncaught exception is encountered. Generally, when an exception is not handled, the threads stack trace is printed to the error stream and the throwing thread dies; potentially causing the application to shut down if there are no other active (or daemon) threads running.

If your application runs as a server, then there will likely be multiple threads (created by the IO libraries) which are used to respond to the incoming requests. This makes it hard to implement a consistent strategy that can handle all uncaught exceptions in a uniform way.

The following program illustrates how to register a default policy for handling uncaught exceptions:

public class TestMain {
  public static void main(String[] args) {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
      @Override
      public void uncaughtException(Thread t, Throwable e) {
        if (e instanceof InvocationTargetException) {
          e = e.getCause();
        }
        //handle all uncaught exceptions here
        System.out.println("Got exception with message: " + e.getMessage());
      }
    });
    throw new RuntimeException("Gonna die!");
  }
}

Setting the default exception handler (line 3) will alter the default behavior for handling uncaught exceptions in the JVM. The implementation of the uncaughtException method (lines 6-10) will now determine what should be done. In this case just the message from the exception will be printed to standard out. A more real-world application of this might be to send a warning message to an operations team, or to take some other remedial action.

The caveat to this approach is that the default exception handler will only be used in cases where neither the offending Thread, or the ThreadGroup that it belongs to, have had their uncaught exception handlers set. If your application manages its own threads, then this will likely not be a problem for you. If your application runs in an application server, then you might well find that the application server has set these handlers already.

Comments 2

  1. Steve Neal

    Hi Yogesh,

    There’s an RSS link at the top of the page that you can use to follow this blog. I don’t have support for email notification at the moment.

    Steve.


    Yogesh:

    wow, thats really nice. Can I follow this blog?
    I mean i would like to automatic e-mails from this blog when ever new content is posted.

Leave a Reply

Your email address will not be published. Required fields are marked *