UncaughtExceptionHandler in Java

If you do not handle a runtime exception in your program, the default behaviour will be to terminate the program and dump the call stacktrace on the console. Java provides an elegant mechanism of handling Runtime Exceptions that you might have not handled in your program. UncaughtExceptionHandler can be defined at three levels. From highest to lowest they are:

  1. Thread.setDefaultUncaughtExceptionHandler
  2. ThreadGroup.uncaughtException
  3. Thread.setUncaughtExceptionHandler

Uncaught exception handling is controlled first by the thread, then by the thread’s ThreadGroup object and finally by the default uncaught exception handler. If the thread does not have an explicit uncaught exception handler set, and the thread’s thread group (including parent thread groups) does not specialize its uncaughtException method, then the default handler’s uncaughtException method will be invoked. By setting the default uncaught exception handler, an application can change the way in which uncaught exceptions are handled (such as logging to a specific device, or file, or sending an email etc) for those threads that would already accept whatever “default” behavior the system provided. Here are examples of how this is done. Example 1: Default Uncaught Exception Handler

package com.bharat.threads;

/**
 * This example demonstrates use of Global exception handler 
 * @author Bharat Sharma
 *
 */
public class DefaultUncaughtExceptionHandler
{

  public static void main(String... args){
    
    
    // Register a Default Uncaught Exception Handler for your program
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
    {
      
      @Override
      public void uncaughtException(Thread t, Throwable e)
      {
        // do some good stuff here, like logging or sending an alert email to the Support team
        System.out.println("Handled by global Exception handler");
        System.out.println(e.getMessage());
      }
    });
        
    // somewhere down the line your program throws an exception.
    // this should get handled by Default Uncaught exception handler that we have registered.
    throw new RuntimeException("My Runtime exception..");
  }
}

Output

Handled by global Exception handler
My Runtime exception..

Example 2: ThreadGroup Uncaught Exception Handler

package com.bharat.threads;

/**
 * This example demonstrates use of Thread Group exception handler
 * @author Bharat Sharma
 *
 */

public class ThreadGroupUncaughtExceptionHandler
{

  public static void main(String[] args){
    
    MyThreadGroup tg = new MyThreadGroup("my thread group");
    
    // Create a thread and assign it to myThreadGroup
    Thread t = new Thread(tg, new Runnable()
    {
      
      @Override
      public void run()
      {
        System.out.println("My thread is running");
        
        // somewhere during execution your thread throws a runtime exception.
        throw new RuntimeException("Exception occured..");    
      }
    });
    t.start();
   
  }
}


/**
 * A ThreadGroup that overides the uncaughtException method
 * @author Bharat Sharma
 *
 */
class MyThreadGroup extends ThreadGroup{

  
  public MyThreadGroup(String name)
  {
    super(name);
  }
  
  // put your exception handling code here.
  @Override
  public void uncaughtException(Thread thread, Throwable t){
    
    System.out.println(t.getMessage());
    System.out.println("Handled by myThreadGroup!");
    
  }
}

Output:

My thread is running
Exception occured..
Handled by myThreadGroup!

Example 3: Thread Uncaught Exception Handler, handles uncaught exceptions in the current thread.

package com.bharat.threads;

/**
 * Demonstrates the use of Uncaught exception handler for current thread
 * @author Bharat Sharma
 *
 */
public class UncaughtExceptionHandler 
{

  public static void main(String[] args) throws Exception{
    
    Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
    {
      
      // Your exception handling code goes inside this method.
      @Override
      public void uncaughtException(Thread t, Throwable e)
      {
        System.out.println("handled! : "+ e.getMessage());
      }
      
    });
  
    // assume exception occured during execution of this thread.
    // here our thread is Main Thread.
    throw new RuntimeException("Runtime exception thrown from somewhere in your program");
    
  }
}

Output

handled! : Runtime exception thrown from somewhere in your program
Advertisements

, , , , , , , ,

  1. Leave a comment

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

%d bloggers like this: