You can set UncaughtExceptionHandler for the thread controlling the code above:

// t is the parent code thread
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

    public void uncaughtException(Thread t, Throwable e) {
       LOGGER.error(t + " throws exception: " + e);
    }
 });

Java docs for UncaughtExceptionHandler -

When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException method, passing the thread and the exception as arguments

the setUncaughtExceptionHandler is commonly used to free memory or kill threads that the system will not be able to kill, and perhaps, remain zombie.

A real example:

Thread t = new Thread(new MyRunnable());
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

    public void uncaughtException(Thread t, Throwable e) {
       LOGGER.error(t + " throws exception: " + e);
    }
});
t.start();

//outside that class
class MyRunnable implements Runnable(){
    public void run(){
        throw new RuntimeException("hey you!");
    }
}
Answer from RamonBoza on Stack Overflow
🌐
BtechSmartClass
btechsmartclass.com › java › java-uncaught-exceptions.html
Java Tutorials - Uncaught Exceptions in Java
The uncaught exceptions are the exceptions that are not caught by the compiler but automatically caught and handled by the Java built-in exception handler.
🌐
GeeksforGeeks
geeksforgeeks.org › java › thread-uncaughtexceptionhandler-in-java-with-examples
Thread UncaughtExceptionHandler in Java with Examples - GeeksforGeeks
July 15, 2025 - 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 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 Sy
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › lang › Thread.UncaughtExceptionHandler.html
Thread.UncaughtExceptionHandler (Java Platform SE 7 )
Method invoked when the given thread terminates due to the given uncaught exception. Any exception thrown by this method will be ignored by the Java Virtual Machine.
🌐
Java Mex
javamex.com › tutorials › exceptions › exceptions_uncaught_handler.shtml
How uncaught exceptions are handled in Java
When an uncaught exception occurs in a particular thread, Java looks for what is called an uncaught exception handler, actually an implementaiton of the interface UncaughtExceptionHandler. The latter interface has a method handleException(), which the implementer overrides to take appropriate action, such as printing the stack trace to the console.
Top answer
1 of 4
35

You can set UncaughtExceptionHandler for the thread controlling the code above:

// t is the parent code thread
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

    public void uncaughtException(Thread t, Throwable e) {
       LOGGER.error(t + " throws exception: " + e);
    }
 });

Java docs for UncaughtExceptionHandler -

When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException method, passing the thread and the exception as arguments

the setUncaughtExceptionHandler is commonly used to free memory or kill threads that the system will not be able to kill, and perhaps, remain zombie.

A real example:

Thread t = new Thread(new MyRunnable());
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

    public void uncaughtException(Thread t, Throwable e) {
       LOGGER.error(t + " throws exception: " + e);
    }
});
t.start();

//outside that class
class MyRunnable implements Runnable(){
    public void run(){
        throw new RuntimeException("hey you!");
    }
}
2 of 4
5

You can use UncaughtExceptionHandler to handle the exception those causes a thread to terminate abruptly. Java doc for UncaughtExceptionHandler -

Interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception. When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException method, passing the thread and the exception as arguments

You need to implement this interface and set your implementation of UncaughtExceptionHandler for a thread by using method setUncaughtExceptionHandler. There are two ways you can do this -

  1. setUncaughtExceptionHandler
  2. setDefaultUncaughtExceptionHandler

1) setUncaughtExceptionHandler - This will be a thread specific exception handler. So in case this thread gets terminated by some unhandled exception, this handler will be used.

2) setDefaultUncaughtExceptionHandler - This will be a default exception handler in case there is no specific uncaught exception handler for a thread.

Example -

class MyExceptionHandler implements UncaughtExceptionHandler{
    @Override
    public void uncaughtException(Thread arg0, Throwable arg1) {
        System.out.println("[DEFAULT EXCEPTION HANDLER] Caught some exception");
    }
}

class MyThread extends Thread{
    public MyThread() {
        setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("[THREAD SPECIFIC] My exception handler");
            }
        });
    }
    public void run(){
        throw new RuntimeException();
    }
}

public class Test {

    public static void main(String[] args) {
        Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
        new MyThread().start();
        // current thread does not have a thread specific exception handler
        throw new RuntimeException();
    }

}
🌐
Mayhem Security
mayhem.security › blog › what-is-an-uncaught-exception-error
What Is An Uncaught Exception Error? | Mayhem
CWE 248-Uncaught Exception occurs when an exception is not caught by a programming construct or by the programmer, it results in an uncaught exception. In Java, for example, this would be an unhandled exception that would terminate the program.
🌐
Better Stack
betterstack.com › community › questions › how-to-log-uncaught-exceptions-in-java
How to log uncaught exceptions in Java | Better Stack Community
Now, if an uncaught exception occurs in any thread of your Java application, the CustomUncaughtExceptionHandler class's uncaughtException method will be called, and it will log the exception details using a logger (in this case, the Java Logger class).
🌐
O'Reilly
oreilly.com › library › view › java-a-beginners › 9780071606325 › ch9lev1sec3.html
The Consequences of an Uncaught Exception - Java, A Beginner's Guide, 5th Edition, 5th Edition [Book]
Catching one of Java’s standard ... caught by some piece of code, somewhere. In general, if your program does not catch an exception, then it will be caught by the JVM....
Find elsewhere
🌐
Quora
quora.com › What-is-uncaught-exception-in-Java
What is uncaught exception in Java? - Quora
Answer: It's the one that will cause the jvm to exit in an inelegant manner. If the exception is not caught at execution time, it will continue to “bubble” up to the main method.
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Provide an uncaught exception handler
package hirondelle.movies.exception; import hirondelle.movies.util.Util; import hirondelle.movies.util.ui.UiUtil; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.logging.Logger; import javax.swing.JOptionPane; /** Custom handler for any uncaught exceptions. <P>By default, a Swing app will handle uncaught exceptions simply by printing a stack trace to {@link System#err}. However, the end user will not usually see that, and if they do, they will not likely understand it. This class addresses that problem, by showing the end user a simple error message in a modal dialog.
🌐
TutorialsPoint
tutorialspoint.com › home › articles on trending technologies › how to handle the exception using uncaughtexceptionhandler in java?
How to handle the exception using UncaughtExceptionHandler in Java?
July 30, 2019 - 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); } } } The Exception Caught: java.lang.Exception: Test Exception
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › lang › Thread.UncaughtExceptionHandler.html
Thread.UncaughtExceptionHandler (Java SE 17 & JDK 17)
July 15, 2025 - Interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception. When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException method, passing the thread and the exception as arguments.
🌐
Javatpoint
javatpoint.com › uncaught-exception-in-java
Uncaught Exception in Java - Javatpoint
Uncaught Exception in Java with java tutorial, features, history, variables, programs, operators, oops concept, array, string, map, math, methods, examples etc.
🌐
Medium
medium.com › @yosimizrachi › advanced-exception-handling-thread-uncaughtexceptionhandler-c72e013da092
Advanced exception handling in Java -Thread.UncaughtExceptionHandler | by Yosi Mizrachi | Medium
July 18, 2020 - So basically when a thread such as the main thread is about to terminate due to an uncaught exception the 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.
🌐
Android Developers
developer.android.com › api reference › thread.uncaughtexceptionhandler
Thread.UncaughtExceptionHandler | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
Baeldung
baeldung.com › home › java › java global exception handler
Java Global Exception Handler | Baeldung
January 8, 2024 - Next, we’ll consider the Global Exception Handler, as a generic way to handle exceptions. The instances of the RuntimeException are optional to handle. Consequently, it still leaves a window open for getting the long stack traces at runtime. To handle this, Java provides the UncaughtExceptionHandler interface.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Thread.UncaughtExceptionHandler.html
Thread.UncaughtExceptionHandler (Java Platform SE 8 )
July 15, 2025 - Method invoked when the given thread terminates due to the given uncaught exception. Any exception thrown by this method will be ignored by the Java Virtual Machine.
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › docs › api › java.base › java › lang › Thread.UncaughtExceptionHandler.html
Thread.UncaughtExceptionHandler (Java SE 21 & JDK 21)
July 15, 2025 - Method invoked when the given thread terminates due to the given uncaught exception. Any exception thrown by this method will be ignored by the Java Virtual Machine.
🌐
Tpoint Tech
tpointtech.com › uncaught-exception-in-java
Uncaught Exception in Java - Tpoint Tech
Structured Concurrency in Java · Uncaught Exception in Java · ValueOf() Method in Java · Virtual Thread in Java · Difference Between Constructor Overloading and Method Overloading in Java · Difference Between for loop and for-each Loop in Java · Difference Between Fork/Join Framework and ExecutorService in Java ·