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 :


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


The Thread throwing Runtime Exception :


package com.jcg.example;

 * @author anirudh
public class TestThread implements Runnable{

	public void run() {
		throw new RuntimeException();


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

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


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.
Notify of

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

Inline Feedbacks
View all comments
Back to top button