0

I would like to know how to handle exceptions from my Callable when I use Void as a return type.

Something like this:

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            call a third party code where an exception is thrown...
            return null;
        }

});

Since I don't need any result from this callable I don't call get() on the Future returned from calling executor.submit(). Thus the exception is swallowed.

What is the right way to handle such exceptions?

Jan Krakora
  • 2,500
  • 3
  • 25
  • 52

1 Answers1

3

How about try/catch within your call() method? - I suppose it depends on what you want to do if an exception occurs.

public Void call() throws Exception {
    try {
        ThirdParty.doSomething();
    } catch(SomeTypeException e) {
        SomeErrorHandler.handleThisError(e); // E.g. report it to the user
    }
    return null;
}
Arve
  • 8,058
  • 2
  • 22
  • 25
  • I just need to push the exception up in calling stack. Our application catches all runtime exceptions and shows a dialog for the user. – Jan Krakora Jul 31 '14 at 09:14
  • @Behnil That's obviously impossible for a task you fork off to another thread. That thread has its own call stack, where at the top is a call to your submitted task. There is no exception handler there if you don't put it in. – Marko Topolnik Jul 31 '14 at 09:17
  • It won't appear on the same stack, as it is executed on the thread of the Executor. – Arve Jul 31 '14 at 09:17