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:
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.
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:
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.
Exception Handled Exception
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.