有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何捕获未来的自定义异常?

通常在运行Future并等待结果时,我只能捕获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?
        }
    }
}

共 (2) 个答案

  1. # 1 楼答案

    假设选中了CustomException,这是不可能的,因为该语言不允许您为此类异常添加catch,该异常不是Future#get()签名的一部分,因此此方法永远无法抛出(这是其契约的一部分)。在您的代码中,注释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.

  2. # 2 楼答案

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

    例如:

    catch (CustomException e) {
    
    } catch (InterruptedException | ExecutionException e) {
    
    }
    
    // It could be even there if CustomException is not extended from InterruptedException | ExecutionException