UncaughtExceptionHandler of Thread

UncaughtExceptionHandleris the hook to handle thread exception. Default exception handler is null if not set. The logic defined in ThreadGroup will be applied. It prints out exception stack trace to system.err.

To define a default handler for all, call the static Thread.setDefaultUncaughtExceptionHandler method. Call instance method thread.setUncaughtExceptionHandler to customize handler by thread.

import java.lang.Thread.UncaughtExceptionHandler;

public class UCETest {

  static class CustomExceptionHandler implements UncaughtExceptionHandler {
    public void uncaughtException(Thread t, Throwable e) {
      System.out.println("Thread " + t.getName() + " terminates with Exception");
      e.printStackTrace();
    }
  }

  public static void main(String ...args) {
    new Thread(() -> {
      throw new RuntimeException("error1");
    }, "ThreadGroupHandler").start();  

    Thread thread = new Thread(() -> {
      throw new RuntimeException("error2"); 
    }, "CustomHandler");
    thread.setUncaughtExceptionHandler(new CustomExceptionHandler());
    thread.start();
  } 
}