how to handle java.util.concurrent.ExecutionException exception?
Asked Answered
A

3

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.

Armandarmanda answered 25/7, 2012 at 18:25 Comment(0)
W
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.

Whirlwind answered 25/7, 2012 at 18:30 Comment(0)
Q
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.

Quire answered 25/7, 2012 at 18:31 Comment(0)
R
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
        }

        ...
    }

    ...
}
Radiotelegraph answered 25/7, 2012 at 18:28 Comment(0)
W
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.

Whirlwind answered 25/7, 2012 at 18:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.