Thread.UncaughtExceptionHandler Example
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.
If the thread has not explicitly set UncaughtExceptionHandler, its ThreadGroup object will act as its UncaughtExceptionHandler and exhibit the default behaviour of dumping the stacktrace on the console.
Lets see this in an example, in this example we will make a thread throw Runtime Exception and will handle it via UncaughtExceptionHandler
:
JavaUncaughtExceptionHandlerExample.java
package com.jcg.example; /** * * @author anirudh * */ public class JavaUncaughtExceptionHandlerExample { 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(); } }
The Thread throwing Runtime Exception :
TestThread.java
package com.jcg.example; /** * * @author anirudh * */ public class TestThread implements Runnable{ @Override public void run() { throw new RuntimeException(); } }
Output:
Thread-0 throws exception: java.lang.RuntimeException
In the example above we have set UncaughtExceptionHandler for the thread, and as soon as the thread "TestThread"
shows runtime exception it is handled by this handler.
Download Source Code
So, In this example we saw how we can use Thread.UncaughtExceptionHandler
in Java.
You can download the full source code of this example here : JavaUncaughtExceptionHandlerExample.zip