I prefer to have the exception handling logic further up in the call stack, near the main method. I like this approach... However, I created a thread where some of its metho
With Thread.setUncaughtExceptionHandler() you can set an Thread.UncaughtExceptionHandler in your Thread
and have a centralized logic of handling exceptions of your threads.
Moreover you can write your own ThreadFactory that will create you threads with preset Thread.UncaughtExceptionHandler
.
Catch it at the outer level of your run() method then place the Exception in a variable in your Runnable and have your Runnable indicate that it completed.
The code that started your runnable has to then examine the Runnable to see that the "Exception" object is set and either rethrow it or deal with it.
If you rethrow it, you may want to wrap it in a new exception:
throw new Exception(oldException);
This will give you both stack traces.
(Thanks Taylor L)
You can use an ExecutorService here to submit a callable and receive a Future. At the point you would at the very least want the Exception to be propagated to the invoking thread you would invoke future.get()
future.get() will propogate any exception thrown in the call method to the thread that is invoking future.get(). So if your main thread invokes future.get() then the main thread will see any exceptions thrown.