Share on Google+Share on Google+

Java Thread setUncaughtExceptionHandlermethod

Advertisement
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

Advertisements

Posted on: October 20, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.