如何捕捉期货的自定义异常?

How to catch custom exceptions of Futures?

一般在运行一个Future等待结果的时候,我只能catch InterruptedException | ExecutionException.

但是如果任务抛出一个我想显式捕获的 CustomException 怎么办?我能比检查 e.getCause() instanceof CustomException 做得更好吗?

List<Future> futures; //run some task

for (Future future : futures) {
    try {
        future.get(); //may throw CustomException 
    } catch (InterruptedException | ExecutionException e) {
        if (e.getCause() instanceof CustomException) {
            //how to catch directly?
        }
    }
}

假设选中CustomException,这是不可能的,因为该语言不允许您为不属于Future#get()签名的此类异常添加catch,因此永远不会被这种方法抛出(这是它的合同的一部分)。在您的代码中,注释 may throw CustomException 在那里是因为 您知道 特定于此 Future 的任务的实现。就 Future 接口的 get 方法而言,任何此类特定于实现的异常都将被包装为 ExecutionException.

的原因

此外,使用 e.getCause() 检查此类自定义异常的正确方法,如 ExecutionException 的文档中明确提到的:

Exception thrown when attempting to retrieve the result of a task that aborted by throwing an exception. This exception can be inspected using the getCause() method.

你可以捕获任意多的异常,但它应该是 按照特定的顺序,更广泛的异常必须在子类异常之后。

例如:

catch (CustomException e) {

} catch (InterruptedException | ExecutionException e) {

}

// It could be even there if CustomException is not extended from InterruptedException | ExecutionException