Java Thread setUncaughtExceptionHandlermethod


 

Java Thread setUncaughtExceptionHandlermethod

In this section, we will discuss about UncaughtExceptionHandler method with example.

In this section, we will discuss about UncaughtExceptionHandler method with example.

Java Thread setUncaughtExceptionHandler method

In this section, we will discuss about UncaughtExceptionHandler method with example.

Thread UncaughtExceptionHandler :

In unchecked exceptions ,which are not caught in a try/catch block, then java print the exception stack trace and then terminate your program. Java handles these uncaught exceptions as per the thread in which they are working. An uncaught exception handler handles the occurred uncaught exception in a specified thread.

setUncaughtExceptionHandler() : This method sets the handler called when given thread suddenly terminates due to an uncaught exception.

Example :  In this example we are handling uncaught exception.

  
public class UncaughtExceptionHandler {
  public static void main(String[] args) {
    Thread thread = new Thread(new ExceptionThread());
    thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
      public void uncaughtException(Thread thread, Throwable e) {
        System.out.println(thread + " throws exception: " + e);
      }
    });
    thread.start();
  }
}

class ExceptionThread implements Runnable {
  public void run() {
    throw new ArithmeticException();
  }

}

Output :

Thread[Thread-0,5,main] throws exception: java.lang.ArithmeticException

Ads