Java Threads: Thread and Exception Handling

Whenever an uncaught exception occurs in a thread’s run method we get a default exception dump which gets printed on System.err stream. We may not always want to live with this default behavior and might think about logging the exception message in a more sophisticated way or doing something else as per business requirement.

Such custom exception handling can be achieved using the UncaughtExceptionHandler interface of the Thread class. The ThreadGroup class also implements the Thread.UncaughtExceptionHandler interface. The interface has only one method defined, which is:

void uncaughtException(Thread t, Throwable e);

This handler interface is invoked when a thread abruptly terminates due to an uncaught exception. The below excerpt from Java documentation explains the UncaughtExceptionHandler interface:

When a thread is about to terminate due to an uncaught exception the Java Virtual Machine 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 a thread has not had its UncaughtExceptionHandler explicitly set, then its ThreadGroup object acts as its UncaughtExceptionHandler. If the ThreadGroup object has no special requirements for dealing with the exception, it can forward the invocation to the default uncaught exception handler.

Thread class has two methods viz. setDefaultUncaughtExceptionHandler() and setUncaughtExceptionHandler(). The setDefaultUncaughtExceptionHandler() which is a static method of Thread class can be used to provide a common exception handler for all the threads. On the other hand setUncaughtExceptionHandler() is a non static method of Thread class which is used to provide handler to a given thread.

The below example shows how to handle the uncaught exception thrown from a Thread:

MyThreadTest.java

package com.technicalmusings.examples.thread;

/**
* The below class creates a thread which is supposed to throw an exception.

* A handler is added to the thread before calling the start method of thread.
* When the thread executes the exception is handled by the handler
* and the custom exception message is displayed on the console.
*/

public class MyThreadTest {

public static void main(String[] args) {

Thread newThread = new Thread(new ThreadWithException());

// Add the handler to the thread object
newThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){

@Override
public void uncaughtException(Thread t, Throwable e) {

System.out.println("ERROR! An exception occurred in " + t.getName() + ". Cause: " + e.getMessage());
}
});

newThread.start();
}
}

/**
* This thread throws a custom exception in its run method.
*/

class ThreadWithException implements Runnable {

@Override
public void run() {
throw new RuntimeException("Application Specific Exception!!");
}
}

Output:

ERROR! An exception occurred in Thread-0. Cause: Application Specific Exception!!

Enjoy Learning,
Kamlesh

Advertisements

8 thoughts on “Java Threads: Thread and Exception Handling

  1. ERROR! An exception occurred in Thread-0. Cause: Application Specific Exception!!
    shall we get only this message after all the hard work???

    • Hi mylemons,

      This is a good question and answer depends more or less on the business requirement.

      However you can consider a scenario where you want to handle the thread failure by sending a notification to some other service/person or want to update some status flag in the database indicating the thread failure. All these kind of actions could be taken using this approach.

      Hope this answers your question,
      Kamlesh

  2. hi kamlesh
    thanks for the reply
    but i meant to say is, can we not have a stack trace so that we can reach the root of the bug.
    and is it a good practice to save a flag in the database whenever an error occurs. in that case we need to configure an email message to be sent to somebody who can handle this. in few cases developers dont have access to the production database.

  3. HI, thanks for the above post! I am developing a multithreaded application, in which a main program creates 3 threads. i do not have any application specific exceptions. I want to handle an efficient way of exception handling for the threads. shall i go ahead with the traditional try/catch or any uncaughtexception handlers shud be used? if so, can you please give samples, how do i handle all the generic exceptions in the run() method.Looking forward for your response.

    • You don’t need an application specific exception for using the thread’d exception handler method. If your requirement is to handle all the exceptions I believe the Thread class’s static method setDefaultUncaughtExceptionHandler() can be useful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s