两者的区别是什么
try {
fooBar();
} finally {
barFoo();
}和
try {
fooBar();
} catch(Throwable throwable) {
barFoo(throwable); // Does something with throwable, logs it, or handles it.
}我更喜欢第二个版本,因为它让我可以访问Throwable。这两种变体之间是否存在逻辑上的差异或首选约定?
另外,有没有办法访问finally子句中的异常?
发布于 2010-05-18 14:17:06
这是两件不同的事情:
在您的示例中,您还没有展示第三种可能的构造:
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块也会被执行。
当然,您可以在块外部声明一个保存异常的变量,并在catch块内赋值。之后,您可以在finally块中访问此变量。
Throwable throwable = null;
try {
// do some stuff
}
catch( Throwable e ) {
throwable = e;
}
finally {
if( throwable != null ) {
// handle it
}
}发布于 2010-05-18 14:17:50
这些不是变体,它们是根本不同的东西。始终执行finally,仅在发生异常时执行catch。
发布于 2010-05-18 23:12:13
Finally和catch块有很大的不同:
所以
try {
//some code
}
catch (ExceptionA) {
// Only gets executed if ExceptionA
// was thrown in try block
}
catch (ExceptionB) {
// Only executed if ExceptionB was thrown in try
// and not handled by first catch block
}不同于
try {
//some code
}
finally {
// Gets executed whether or not
// an exception was thrown in try block
}重要的是。
如果定义try块,则必须定义
所以下面的代码也是有效的:
try {
//some code
}
catch (ExceptionA) {
// Only gets executed if
// ExceptionA was thrown in try block
}
catch (ExceptionB) {
// Only executed if ExceptionB was thrown in
// try and not handled by first catch block
}
//even more catch blocks
finally {
// Gets executed whether or not an
// exception was thrown in try block
}https://stackoverflow.com/questions/2854910
复制相似问题