Java - Uncaught Exception in Thread


You can handle an uncaught exception thrown in your thread.

java.lang.Thread.UncaughtExceptionHandler interface defined as a nested static interface in the Thread class.

It has the following one method defined:

void uncaughtException(Thread t, Throwable e);

The following code implements the Thread.UncaughtExceptionHandler and then register it to the current thread.


class CatchAllThreadExceptionHandler implements Thread.UncaughtExceptionHandler {
  public void uncaughtException(Thread t, Throwable e) {
    System.out.println("Caught Exception from Thread:" + t.getName());
  }//from   ww w. j  a v  a2 s .  c o  m

public class Main {
  public static void main(String[] args) {
    CatchAllThreadExceptionHandler handler = new CatchAllThreadExceptionHandler();

    // Set an uncaught exception handler for main thread

    // Throw an exception
    throw new RuntimeException();