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

Deadly 提交于 2019-12-04 09:38:05

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.

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.

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
        }

        ...
    }

    ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!