What is the best way to handle an ExecutionException?

后端 未结 11 1702
遇见更好的自我
遇见更好的自我 2020-12-04 12:07

I have a method that performs some task with a timeout. I use the ExecutorServer.submit() to get a Future object, and then I call future.get() with a timeout. This is workin

11条回答
  •  不思量自难忘°
    2020-12-04 12:55

    The javadoc of java.util.concurrent.Future.get() states the following. Then why not just catch ExecutionException (and Cancellation and Interrupted as declared by the java.util.concurrent.Future.get()) method?

    ...
    Throws:

    CancellationException - if the computation was cancelled

    ExecutionException - if the computation threw an exception

    InterruptedException - if the current thread was interrupted while waiting

    So basically you can throw whatever exception within your callable and just catch ExecutionException. Then ExecutionException.getCause() will hold the actual exception your callable threw as stated in the javadoc. This way you are shielded from method signature changes related to checked exception declaration.

    By the way you should never catch Throwable, as this would catch also RuntimeExceptions and Errors. Catching Exception is a little bit better but still not recommended, as it will catch RuntimeExceptions.

    Something like:

    try {  
        MyResult result = myFutureTask.get();
    } catch (ExecutionException e) {
        if (errorHandler != null) {
            errorHandler.handleExecutionException(e);
        }
        logger.error(e);
    } catch (CancellationException e) {
        if (errorHandler != null) {
            errorHandler.handleCancelationException(e);
        }
        logger.error(e);                
    } catch (InterruptedException e) {
        if (errorHandler != null) {
            errorHandler.handleInterruptedException(e);
        }
        logger.error(e);
    }
    

提交回复
热议问题