UncaughtExceptionHandler

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.

Download
You can download the full source code of this example here : JavaUncaughtExceptionHandlerExample.zip

Anirudh Bhatnagar

Anirudh is a Java programmer with extensive experience in building Java/J2EE applications. He has always been fascinated by the new technologies and emerging trends in software development. He has been involved in propagating these changes and new technologies in his projects. He is an avid blogger and agile enthusiast who believes in writing clean and well tested code.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button