What is Thread getUncaughtExceptionHandler() in Java?

The Thread.getUncaughtExceptionHandler() function from the java.lang.Thread class is used to return the handler. It is invoked when the thread is terminated because of an uncaught exception.

It is used for exception handling in threads.

Syntax


Thread.UncaughtExceptionHandler getUncuaghtExceptionHandler()

Parameters

This function does not take any argument values.

Return value

Thread.UncaughtExceptionHandler: This function returns an object of the UncaughtExceptionHandler type.

Example

We can understand the working of Thread.getUncaughtExceptionHandler() through the following code.

// Load library
import java.lang.Thread;
public class Thread_example implements Runnable {
Thread thrd;
public Thread_example() {
thrd = new Thread(this);
// calling run() method
thrd.start();
}
public void run() {
// printing the name of thread
System.out.println("Thread :" + thrd.getName());
/* will return the handler invoked when the thread is stopped because of an uncaught exception. */
Thread.UncaughtExceptionHandler handler =
thrd.getUncaughtExceptionHandler();
System.out.println(handler);
}
public static void main(String[] args) {
new Thread_example();
new Thread_example();
}
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources