How to handle the exception using UncaughtExceptionHandler in Java?

JavaObject Oriented ProgrammingProgramming

The UncaughtExceptionHandler is an interface inside a Thread class. When the main thread is about to terminate due to an uncaught exception the java virtual machine will invoke the thread’s UncaughtExceptionHandler for a chance to perform some error handling like logging the exception to a file or uploading the log to the server before it gets killed. We can set a Default Exception Handler which will be called for the all unhandled exceptions. It is introduced in Java 5 Version.

This Handler can be set by using the below static method of java.lang.Thread class.

public static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler ueh)

We have to provide an implementation of the interface Thread.UncaughtExceptionHandler, which has only one method.

Syntax

@FunctionalInterface
public interface UncaughtExceptionHandler {
   void uncaughtException(Thread t, Throwable e);
}

Example

Live Demo

public class UncaughtExceptionHandlerTest {
   public static void main(String[] args) throws Exception {
      Thread.setDefaultUncaughtExceptionHandler(new MyHandler());
      throw new Exception("Test Exception");
   }
   private static final class MyHandler implements Thread.UncaughtExceptionHandler {
      @Override
      public void uncaughtException(Thread t, Throwable e) {
         System.out.println("The Exception Caught: " + e);
      }
   }
}

Output

The Exception Caught: java.lang.Exception: Test Exception
raja
Published on 01-Jul-2019 11:15:19
Advertisements