Catching thread exceptions from Java ExecutorService

Consider calling execute() instead of submit() on the ExecutorService. A Thread invoked with execute() will invoke the Thread.UncaughtExceptionHandler when it fails.

Simply make a ThreadFactory that installs a Thread.UncaughtExceptionHandler on all Threads and then invoke your work with execute() on the ExecutorService instead of submit().

Have a look at this related stack overflow question.


I don't believe there is a standard 'hook' to get to these exceptions when using submit(). However, if you need to support submit() (which sounds reasonable, given that you use a Callable), you can always wrap the Callables and Runnables :

ExecutorService executor = new ThreadPoolExecutor(1, 10, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>()) {
    @Override
    public <T> Future<T> submit(final Callable<T> task) {
        Callable<T> wrappedTask = new Callable<T>() {
            @Override
            public T call() throws Exception {
                try {
                    return task.call();
                }
                catch (Exception e) {
                    System.out.println("Oh boy, something broke!");
                    e.printStackTrace();
                    throw e;
                }
            }
        };

        return super.submit(wrappedTask);
    }
};

Of course, this method only works if you're the one building the ExecutorService in the first place. Furthermore, remember to override all three submit() variants.


As explained in this thread What is the difference between submit and execute method with ThreadPoolExecutor, using execute will only work if you implement Runnable and not Callable as execute cannot return a Future.

I think in your scenario you should build the future object so that it can accommodate the exception stuff also. So in case of exception you build the error message object.