How to catch exception thrown by a thread

In this example we will see how to use Thread.UncaughtExceptionHandler. UncaughtExceptionHandler is used as a way to provide an elegant way to handle Runtime Exceptions which are not handled otherwise in the programs.

As soon as a thread terminates due to an uncaught exception,JVM will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler’s uncaughtException method, passing the thread and the exception as arguments.

public class ThreadExceptionHandler {   public static void main(String[] args) {   Thread myThread = new Thread(new TestThread());   myThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {   public void uncaughtException(Thread myThread, Throwable e) {   System.out.println(myThread.getName() + ” throws exception: ” + e);   }   });   // this will call run() function   myThread.start();   }   }   class TestThread implements Runnable {   @Override public void run() {   throw new RuntimeException();   }   }

Leave a Reply

Your email address will not be published. Required fields are marked *