在 Java 中,是否有一种优雅的方法可以在运行 finally 块之前检测是否发生异常?在处理“close()”语句时,通常需要在 finally 块中处理异常。理想情况下,我们希望维护两个异常并将它们向上传播(因为它们都可能包含有用的信息)。我能想到的唯一方法是在 try-catch-finally 范围之外有一个变量来保存对抛出异常的引用。然后将“已保存”异常与 finally 块中发生的任何异常一起传播。
有没有更优雅的方式来做到这一点?也许一个 API 调用会揭示这一点?
这是我正在谈论的一些粗略代码:
Throwable t = null;
try {
stream.write(buffer);
} catch(IOException e) {
t = e; //Need to save this exception for finally
throw e;
} finally {
try {
stream.close(); //may throw exception
} catch(IOException e) {
//Is there something better than saving the exception from the exception block?
if(t!=null) {
//propagate the read exception as the "cause"--not great, but you see what I mean.
throw new IOException("Could not close in finally block: " + e.getMessage(),t);
} else {
throw e; //just pass it up
}
}//end close
}
显然,还有许多其他类似的 kludges 可能涉及将异常保存为成员变量,从方法中返回它等等......但我正在寻找更优雅的东西。
也许类似Thread.getPendingException()
或类似的东西?就此而言,其他语言是否有优雅的解决方案?
这个问题实际上是从另一个问题的评论中产生的,该问题提出了一个有趣的问题。