Say that I have the following code:
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(myRunnable);
Now, if myRunnable throws a RuntimeExcpetion, how can I catch it? One way would be to supply my own ThreadFactory implementation to newSingleThreadExecutor() and set custom uncaughtExceptionHandlers for the Threads that come out of it. Another way would be to wrap myRunnable to a local (anonymous) Runnable that contains a try-catch -block. Maybe there are other similar workarounds too. But… somehow this feels dirty, I feel that it shouldn’t be this complicated. Is there a clean solution?
The clean workaround is to use
ExecutorService.submit()instead ofexecute(). This returns you aFuturewhich you can use to retrieve the result or exception of the task: