Skip to main content

Handling unexpected runtime exception inside Thread. thread.setUncaughtExceptionHandler

Create and set UncaughtExceptionHandler before starting new thread to catch unexpected runtime exception in Multithreading application.

package demo;

public class ExceptionHandler {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                throw new RuntimeException("Critical Error");
            }
        });
        System.out.println("Starting new thread " + Thread.currentThread().getName());
        //Throw this exception if any exception has occurred inside running thread but was not caught anywhere else
        //This should be set before starting the new thread
        thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable throwable) {
                System.out.println("Error occurred on thread: " + thread.getName() + ". Reason : " + throwable.getMessage());
            }
        });

        thread.setName("Bad Thread");

        thread.start();

    }
}


Comments