Logging uncaught exceptions in a Java application

Logging exceptions is pretty important as it allows you to troubleshoot problems that come up with your production applications. If you have a regular Java application, there is a trick to logging uncaught exceptions. Those are the exceptions that do not require you to put your code in a try/catch block. To log these exceptions, you need to set a default uncaught exception handler. The example below defines one that uses log4j to write an ERROR log entry.

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class HelloWorld {
   private static Log _logger = LogFactory.getLog(HelloWorld.class);
   public static void main (String args[]) {
      //setting uncaught exception logging
      Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
         public void uncaughtException(Thread t, Throwable e) {
            _logger.error("An uncaught exception has been thrown", e);          }
      });
   }
}

Short URL for this post: http://tmblr.co/Zd8FQxE1CN-q