11

Some part of my code is throwing java.util.concurrent.ExecutionException exception. How can I handle this? Can I use throws clause? I am a bit new to java.

3 Answers 3

17

It depends on how mission critical your Future was for how to handle it. The truth is you shouldn't ever get one. You only ever get this exception if something was thrown by the code executed in your Future that wasn't handled.

When you catch(ExecutionException e) you should be able to use e.getCause() to determine what happened in your Future.

Ideally, your exception doesn't bubble up to the surface like this, but rather is handled directly in your Future.

Sign up to request clarification or add additional context in comments.

Comments

5

You should investigate and handle the cause of your ExecutionException.

One possibility, described in "Java Concurrency in Action" book, is to create launderThrowable method that take care of unwrapping generic ExecutionExceptions

void launderThrowable ( final Throwable ex )
{
    if ( ex instanceof ExecutionException )
    {
        Throwable cause = ex.getCause( );

        if ( cause instanceof RuntimeException )
        {
            // Do not handle RuntimeExceptions
            throw cause;
        }

        if ( cause instanceof MyException )
        {
            // Intelligent handling of MyException
        }

        ...
    }

    ...
}

Comments

2

If you're looking to handle the exception, things are pretty straightforward.

   public void exceptionFix1() {
       try {
           //code that throws the exception
       } catch (ExecutionException e) {
           //what to do when it throws the exception
       }
   }

   public void exceptionFix2() throws ExecutionException {
       //code that throws the exception
   }

Keep in mind that the second example will have to be enclosed in a try-catch block somewhere up your execution hierarchy.

If you're looking to fix the exception, we'll have to see more of your code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.