Thread UncaughtExceptionHandler in Java with Examples
Last Updated :
10 Jun, 2020
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:
Java
public class GFG {
public static void main(String args[])
{
System.out.println(10 / 0);
}
}
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:
Java
// 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);
}
}
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.
Java
// 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");
}
}
Output:
Exception Handled Exception
Similar Reads
Types of Errors in Java with Examples Error is an illegal operation performed by the user which results in the abnormal working of the program. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Thus errors should be removed befo
8 min read
Java Program to Use Exceptions with Thread Exceptions are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program. When a method encounters an abnormal condition that it can not handle, an exception is thrown as an exception statement. Exceptions are caught
5 min read
How to Handle a java.lang.ArithmeticException in Java? In Java programming, the java.lang.ArithmeticException is an unchecked exception of arithmetic operations. This means you try to divisible by zero, which raises the runtime error. This error can be handled with the ArthmeticException. ArithmeticException can be defined as a runtime exception that ca
2 min read
How to Handle SQLException in JDBC? Java Database Connectivity (JDBC) serves as the backbone for Java applications when interacting with databases. While establishing connections and executing queries, we developers often encounter SQLExceptions, which are inevitable in the real world. Handling those exceptions is crucial in the devel
4 min read
Java Program to Handle Runtime Exceptions RuntimeException is the superclass of all classes that exceptions are thrown during the normal operation of the Java VM (Virtual Machine). The RuntimeException and its subclasses are unchecked exceptions. The most common exceptions are NullPointerException, ArrayIndexOutOfBoundsException, ClassCastE
2 min read
ClosedChannelException in Java with Examples The class ClosedChannelException is invoked when an I/O operation is attempted on a closed channel or a channel that is closed to the attempted operation. That is if this exception is thrown, however, does not imply the channel is completely closed but is closed to the attempted operation. Syntax: p
4 min read
Java Program to Handle Checked Exception Checked exceptions are the subclass of the Exception class. These types of exceptions need to be handled during the compile time of the program. These exceptions can be handled by the try-catch block or by using throws keyword otherwise the program will give a compilation error. Â ClassNotFoundExcept
5 min read
Java Program to Handle Unchecked Exception Exceptions are the issues arising at the runtime resulting in an abrupt flow of working of the program. Remember exceptions are never thrown at the compile-time rather always at runtime be it of any type. No exception is thrown at compile time. Throwable Is super-class of all exceptions and errors t
4 min read
Using throw, catch and instanceof to handle Exceptions in Java Prerequisite : Try-Catch Block in Java In Java, it is possible that your program may encounter exceptions, for which the language provides try-catch statements to handle them. However, there is a possibility that the piece of code enclosed inside the 'try' block may be vulnerable to more than one ex
4 min read
How to Solve IllegalArgumentException in Java? An unexpected event occurring during the program execution is called an Exception. This can be caused due to several factors like invalid user input, network failure, memory limitations, trying to open a file that does not exist, etc. If an exception occurs, an Exception object is generated, contai
3 min read