I am developing a java app I would like to know how to handle exceptions on multiple running threads. Is there any example? Thanks
- 3Have a look over stackoverflow.com/questions/8362345/…Ioan– Ioan2013-06-06 10:28:26 +00:00Commented Jun 6, 2013 at 10:28
- See: stackoverflow.com/questions/6662539/java-thread-exceptions There is a complete explanation and example code.TFuto– TFuto2013-06-06 10:56:40 +00:00Commented Jun 6, 2013 at 10:56
Add a comment |
1 Answer
If I understood your question correctly, you asking how to detect that thread finished due to unhandled exception.
You need to implement UncaughtExceptionHandler for that. The simplest useful activity you can put in your implementation of handler is to log exception which wasn't caught.
One sample of this, used together with Executor:
final Thread.UncaughtExceptionHandler DEFAULT_HANDLER = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { log.error("", e); } }; ExecutorService executorService = Executors.newCachedThreadPool(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setUncaughtExceptionHandler(DEFAULT_HANDLER); return t; } }); executorService.execute(new Runnable() { @Override public void run() { throw new RuntimeException("log me"); } });