Java Thread How to - Catch exception handler for uncaught exception








Question

We would like to know how to catch exception handler for uncaught exception.

Answer

import java.lang.Thread.UncaughtExceptionHandler;
/*from  www.j  a  v  a  2s  . co  m*/
public class Main {
  public static void main(String[] args) {
    Thread thread = new Thread() {
      public void run() {
        throw new NullPointerException();
      }
    };
    thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
      @Override
      public void uncaughtException(Thread arg0, Throwable arg1) {
        arg1.printStackTrace();
      }
    });
    thread.start();
  }
}

The code above generates the following result.