UnCaughtExceptionHandler: There are two kinds of exceptions in Java one is checked exceptions and other is Unchecked exceptions. We already know about checked and unchecked exception.
In this tutorial we will learn about UnCaughtExceptionHandler. Unchecked exceptions don’t have to be caught and when an unchecked exception is thrown inside the run() method of a Thread , the default behavior is to write the stack trace and exit the program.
For this , Java provides an elegant mechanism of handling Runtime Exceptions that is not handled by programmer to avoid the program ending abruptly using UnCaughtExceptionHandler.
When a thread terminates due to an uncaught runtime exception ,JVM will consult the thread for its UncaughtExceptionHandler using method Thread.getUncaughtExceptionHandler() which then will invoke the handler’s uncaughtException method.
If the thread doesn’t have an explicitly UncaughtExceptionHandler then its ThreadGroup will act as its UncaughtExceptionHandler and exhibit the default behavior to write the stacktrace.
Program to demonstrate:
Lets see below program , in this we throw Runtime Exception and handles it using UncaughtExceptionHandler . Inside uncaughtException method of handler we print information about thread which has failed and exception information.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package com.j2eereference; public class UnCaughtExceptionHandlerDemo { public static void main(String[] args) { Thread t = new Thread(new MyRunnableDemo()); t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { System.out.printf("An exception has been handled\n"); System.out.printf("Thread Id: %s\n", t.getId()); System.out.printf("Thread status: %s\n", t.getState()); System.out.printf("Thread priority: %s\n", t.getPriority()); System.out.printf("Exception type: %s: %s\n", e.getClass().getName(), e.getMessage()); System.out.printf("Stack Trace description: \n"); e.printStackTrace(System.out); } }); t.start(); } } class MyRunnableDemo implements Runnable { public void run() { throw new RuntimeException(); } } |
OutPut :
An exception has been handledThread Id: 10
Thread status: RUNNABLE
Thread priority: 5
Exception type: java.lang.RuntimeException: null
Stack Trace description:
java.lang.RuntimeException at com.j2eereference.MyRunnableDemo.run(UnCaughtExceptionHandlerDemo.java:31)at java.lang.Thread.run(Thread.java:745)
Where to use :
- We can use UncaughtExceptionHandler for making logging more informative as well often default logs doesn’t provide enough information about the exception when thread execution failed.
- It can also be used In real life application where programmer would like to start a failed thread more than once to perform a critical task even if it failed couple of times by again starting thread from UnCaughtExceptionHandler.