Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle java.util.concurrent.ExecutionException exception?

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.

like image 758
user811433 Avatar asked Jul 25 '12 18:07

user811433


3 Answers

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.

like image 52
corsiKa Avatar answered Sep 17 '22 10:09

corsiKa


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
        }

        ...
    }

    ...
}
like image 36
Alexander Pogrebnyak Avatar answered Sep 21 '22 10:09

Alexander Pogrebnyak


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.

like image 41
LastStar007 Avatar answered Sep 20 '22 10:09

LastStar007