问题描述
两者之间有什么区别
try {
fooBar();
} finally {
barFoo();
}
和
try {
fooBar();
} catch(Throwable throwable) {
barFoo(throwable); // Does something with throwable, logs it, or handles it.
}
我更喜欢第二个版本,因为它使我可以使用Throwable.两种变体之间是否存在逻辑上的差异或偏好的约定?
I like the second version better because it gives me access to the Throwable. Is there any logical difference or a preferred convention between the two variations?
还可以通过finally子句访问异常吗?
Also, is there a way to access the exception from the finally clause?
推荐答案
这是两件事:
- 仅在try块中引发异常时才执行catch块.
- 无论是否引发异常,finally块总是在try(-catch)块之后执行.
在您的示例中,您没有显示第三个可能的构造:
In your example you haven't shown the third possible construct:
try {
// try to execute this statements...
}
catch( SpecificException e ) {
// if a specific exception was thrown, handle it here
}
// ... more catches for specific exceptions can come here
catch( Exception e ) {
// if a more general exception was thrown, handle it here
}
finally {
// here you can clean things up afterwards
}
而且,就像@codeca在他的评论中说的那样,无法访问finally块内部的异常,因为即使没有异常,也会执行finally块.
And, like @codeca says in his comment, there is no way to access the exception inside the finally block, because the finally block is executed even if there is no exception.
当然,您可以在变量外声明一个包含异常的变量,并在catch块内分配一个值.然后,您可以在finally块中访问此变量.
Of course you could declare a variable that holds the exception outside of your block and assign a value inside the catch block. Afterwards you can access this variable inside your finally block.
Throwable throwable = null;
try {
// do some stuff
}
catch( Throwable e ) {
throwable = e;
}
finally {
if( throwable != null ) {
// handle it
}
}
这篇关于try-finally和try-catch之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!