Thread UncaughtExceptionHandler in Java with Examples

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions.

In this article, we will understand how to implement Thread.UncaughtExceptionHandler.

Before implementing the handler, let’s understand how exceptions are caused by an example as follows:

filter_none

edit
close

play_arrow

link
brightness_4
code

public class GFG {
  
    public static void main(String args[])
    {
        System.out.println(10 / 0);
    }
}

chevron_right


The output for the above code is

Exception in thread "main"
 java.lang.ArithmeticException:
 / by zero at Demo.main(GFG.java:5)

However, if we wish to override the internal working of JVM such that a custom message is displayed when an exception occurs, we can use Thread.UncaughtExceptionHandler to handle it.



The setDefaultUncaughtExceptionHandler() method of java.lang.Thread class is used to override the way JVM handles uncaught Exceptions.

Syntax:

public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh)

Parameter: This method takes an object of the type UncaughtExceptionHandler as a parameter.

Below are the examples to illustrate the setDefaultUncaughtExceptionHandler() method:

Example 1: Lets try to create a class which implements the interface UncaughtExceptionHandler from the Thread class to handle a division by 0 exception as follows:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// the exception handler
  
// Creating a random class to
// implement the interface
class Random
    implements Thread
                   .UncaughtExceptionHandler {
  
    // Method to handle the
    // uncaught exception
    public void uncaughtException(
        Thread t, Throwable e)
    {
  
        // Custom task that needs to be
        // performed when an exception occurs
        System.out.println(
            "Welcome to GeeksforGeeks");
    }
}
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // Passing the object of the type
        // UncaughtExceptionHandler to the
        // setter method
        // setDefaultUncaughtExceptionHandler()
        Thread
            .setDefaultUncaughtExceptionHandler(
                new Random());
  
        System.out.println(10 / 0);
    }
}

chevron_right


Output:

Welcome to GeeksforGeeks

Note: The above code doesn’t work on the online IDE because online IDE’s doesn’t give permissions to override the exception handler. Here, the setDefaultUncaughtExceptionHandler() method, changed the field defaultUncaughtExceptionHandler from initial value null to the Random class. The uncaughtException() method of the Random class was invoked, when the uncaught exception occurred.

Example 2: In this example, let’s throw a new exception and understand how the exceptions are handled.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// the exception handler
  
// Creating a random class to
// implement the interface
class Random
    implements Thread.UncaughtExceptionHandler {
  
    // Method to handle the
    // uncaught exception
    public void uncaughtException(
        Thread t, Throwable e)
    {
  
        // Custom task that needs to be
        // performed when an exception occurs
        System.out.println(
            "Exception Handled " + e);
    }
}
  
public class GFG {
  
    public static void main(String[] args)
        throws Exception
    {
  
        // Passing the object of the type
        // UncaughtExceptionHandler to the
        // setter method
        // setDefaultUncaughtExceptionHandler()
        Thread.setDefaultUncaughtExceptionHandler(
            new Random());
  
        throw new Exception("Exception");
    }
}

chevron_right


Output:

Exception Handled Exception

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.