membersound
membersound

Reputation: 86747

How to catch custom exceptions of Futures?

Usually when running a Future and waiting for the result, I can only catch InterruptedException | ExecutionException.

But what if the task throws a CustomException that I want to catch explicit? Could I do any better than checking e.getCause() instanceof CustomException?

List<Future> futures; //run some task

for (Future future : futures) {
    try {
        future.get(); //may throw CustomException 
    } catch (InterruptedException | ExecutionException e) {
        if (e.getCause() instanceof CustomException) {
            //how to catch directly?
        }
    }
}

Upvotes: 2

Views: 3403

Answers (2)

M A
M A

Reputation: 72854

Assuming CustomException is checked, it is not possible because the language does not allow you to add a catch for such an exception that is not part of the Future#get() signature, and hence can never be thrown by this method (this is part of its contract). In your code, the comment may throw CustomException is there because you knew the implementation of the task specific to this Future. As far as the get method of the Future interface is concerned, any such implementation specific exception will be wrapped as the cause of an ExecutionException.

Furthermore, using e.getCause() is the correct way of inspecting such a custom exception as mentioned explicitly in the documentation of ExecutionException:

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

Upvotes: 5

dubace
dubace

Reputation: 1621

You could catch as many exception as you want, but it should be in specific order where more broader exception must go after the sub-classed exception.

For example:

catch (CustomException e) {

} catch (InterruptedException | ExecutionException e) {

}

// It could be even there if CustomException is not extended from InterruptedException | ExecutionException

Upvotes: -1

Related Questions