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?
}
}
}
# 1 楼答案
假设选中了
CustomException
,这是不可能的,因为该语言不允许您为此类异常添加catch
,该异常不是Future#get()
签名的一部分,因此此方法永远无法抛出(这是其契约的一部分)。在您的代码中,注释may throw CustomException
就在那里,因为您知道该Future
特定任务的实现。就Future
接口的get
方法而言,任何此类特定于实现的异常都将被包装为ExecutionException
的原因此外,使用
e.getCause()
是检查ExecutionException
文档中明确提到的自定义异常的正确方法:# 2 楼答案
您可以捕获任意数量的异常,但它应该是 按照特定的顺序,在子类异常之后必须有更广泛的异常
例如: