Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread thread, Throwable exception) { System.err.println("Thread " + thread.getName() + " threw an uncaught exception: " + exception); } });
Thread t = new Thread(new Runnable() { public void run() { throw new RuntimeException("Something went wrong!"); } }); t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread thread, Throwable exception) { System.err.println("Thread " + thread.getName() + " threw an uncaught exception: " + exception); } }); t.start();In this example, we're creating a new thread and setting its default uncaught exception handler using the "setUncaughtExceptionHandler" method. This handler is also an anonymous inner class that prints out a message to the error stream when an exception is thrown. In both of these examples, the Thread class and its UncaughtExceptionHandler interface are part of the Java Standard Library.