Let’s learn thread setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) method in java.
Thread setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) method in java
setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) method set the handler invoked when this thread abruptly terminates due to an uncaught exception.
Syntax
public void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)
Parameters
ueh the object to use as this thread’s uncaught exception handler. If null then this thread has no explicit handler.
Throws
SecurityException – if the current thread is not allowed to modify this thread.
Example
class SetUncaughtExceptionHandlerDemo { public static void main(String[] args) { Thread t = new Thread(new newThread1()); t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { System.out.println(t + " exception thrown : " + e); } }); t.start(); } } class newThread1 implements Runnable { public void run() { throw new RuntimeException(); } }
Output:
Thread[#21,Thread-0,5,main] exception thrown : java.lang.RuntimeException
Also read – Strings in java