Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to catch Exceptions thrown from Callable.call() [duplicate]

Possible Duplicate:
Handling exceptions from Java ExecutorService tasks

I use the ExecutorService from Java for coordinating Threads. For starting the threads I use

pool = new ExecutorService(2); callableResults = pool.invokeAll(threads); 

To collect the result, I use future.get() for each thread. "threads" is a List of Objects from a Class which implements Callable and overrides call().

Now Ive got the following problem. The method call() does throw various specific exceptions. invokeAll() and future.get() throw only InterruptedException.

Where can I catch my specific exceptions which I throw in call()? Or do I have to handle them there? If one of those exceptions is thrown, is the result then a InterruptedException?

like image 456
nano7 Avatar asked Mar 02 '12 14:03

nano7


People also ask

How do you catch callable exceptions?

get() will throw ExecutionException if provided callable threw exception in the past (the exception is stored in the Future ). Exception thrown when attempting to retrieve the result of a task that aborted by throwing an exception. This exception can be inspected using the Throwable. getCause() method.

Why Callable throw exception?

Utilizing Callable to Throw Exceptions One of the benefits of the Callable interface is the fact that it enables us to throw exceptions that are handled outside of the separate thread of execution. For example, suppose we alter our implementation of Callable to force an exception in our call() method.

Can we catch exceptions thrown by another thread?

Yes, it can be done by using Thread. UncaughtExceptionHandler. When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler usingThread.


1 Answers

AFAIR java.util.concurrent.Future.get() will throw ExecutionException if provided callable threw exception in the past (the exception is stored in the Future).

Exception thrown when attempting to retrieve the result of a task that aborted by throwing an exception. This exception can be inspected using the Throwable.getCause() method.

like image 103
Tomasz Nurkiewicz Avatar answered Sep 22 '22 09:09

Tomasz Nurkiewicz