Home Tutorial Java Core Java Thread setUncaughtExceptionHandlermethod


Share on Google+Share on Google+
Java Thread setUncaughtExceptionHandlermethod
Posted on: October 20, 2012 at 12:00 AM
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);

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


Output :

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

Related Tags for Java Thread setUncaughtExceptionHandlermethod :

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.

Posted on: October 20, 2012

Recommend the tutorial

Advertisements Advertisements