http://howtodoinjava.com/2014/12/23/how-to-restart-thread-using-uncaughtexceptionhandler/
class ExceptionHandler implements UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable e) { System.out.printf( "An exception has been captured\n" ); System.out.printf( "Thread: %s\n" , t.getId()); System.out.printf( "Exception: %s: %s\n" , e.getClass().getName(), e.getMessage()); System.out.printf( "Stack Trace: \n" ); e.printStackTrace(System.out); System.out.printf( "Thread status: %s\n" , t.getState()); new Thread( new Task()).start(); } } |
Now add this exception handler to the thread.
class Task implements Runnable { @Override public void run() { Thread.currentThread().setUncaughtExceptionHandler( new ExceptionHandler()); System.out.println(Integer.parseInt( "123" )); System.out.println(Integer.parseInt( "234" )); System.out.println(Integer.parseInt( "345" )); System.out.println(Integer.parseInt( "XYZ" )); //This will cause NumberFormatException System.out.println(Integer.parseInt( "456" )); } } |
Please note that
http://www.javapractices.com/topic/TopicAction.do?Id=229UncaughtExceptionHandler
can be used for making logging more robust only as well without restarting the thread, because often default logs doesn’t provide enough information about the context when thread execution failed.- for the whole Java Runtime, call Thread.setDefaultUncaughtExceptionHandler upon startup
- for a ThreadGroup, override ThreadGroup.uncaughtException
- for a single Thread, call Thread.setUncaughtExceptionHandler