考虑到这段代码,我能绝对确定finally块总是执行的吗,不管something()是什么?
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("I don't know if this will get printed out");
}
考虑到这段代码,我能绝对确定finally块总是执行的吗,不管something()是什么?
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("I don't know if this will get printed out");
}
当前回答
在两种独特的情况下,返回后不会调用finally块:如果首先调用System.exit(),或者JVM崩溃。
让我尽量用最简单的方式回答你的问题。
规则1:finally块始终运行(虽然有例外。但让我们坚持一段时间。)
规则2:当控件离开try或catch块时,finally块中的语句会运行。控制权的转移可能是正常执行、break、continue、goto或return语句的执行或异常传播的结果。
在返回语句的情况下(由于其标题),控件必须离开调用方法,因此调用相应try finally结构的finally块。return语句在finally块之后执行。
如果finally块中也有return语句,它肯定会覆盖try块中挂起的语句,因为它会清除调用堆栈。
您可以在此处找到更好的解释:http://msdn.microsoft.com/en-us/....这一概念在所有高级语言中基本相同。
其他回答
试用间苯二酚示例
static class IamAutoCloseable implements AutoCloseable {
private final String name;
IamAutoCloseable(String name) {
this.name = name;
}
public void close() {
System.out.println(name);
}
}
@Test
public void withResourceFinally() {
try (IamAutoCloseable closeable1 = new IamAutoCloseable("closeable1");
IamAutoCloseable closeable2 = new IamAutoCloseable("closeable2")) {
System.out.println("try");
} finally {
System.out.println("finally");
}
}
测试输出:
try
closeable2
closeable1
finally
这在任何语言中都是事实。。。finally将始终在return语句之前执行,无论该返回在方法体中的何处。如果不是这样的话,finally块就没有什么意义了。
此外,虽然这是一种糟糕的做法,但如果finally块中有一个return语句,它将胜过常规块中的任何其他返回。也就是说,以下块将返回false:
try { return true; } finally { return false; }
从finally块抛出异常也是一样的。
在两种独特的情况下,返回后不会调用finally块:如果首先调用System.exit(),或者JVM崩溃。
让我尽量用最简单的方式回答你的问题。
规则1:finally块始终运行(虽然有例外。但让我们坚持一段时间。)
规则2:当控件离开try或catch块时,finally块中的语句会运行。控制权的转移可能是正常执行、break、continue、goto或return语句的执行或异常传播的结果。
在返回语句的情况下(由于其标题),控件必须离开调用方法,因此调用相应try finally结构的finally块。return语句在finally块之后执行。
如果finally块中也有return语句,它肯定会覆盖try块中挂起的语句,因为它会清除调用堆栈。
您可以在此处找到更好的解释:http://msdn.microsoft.com/en-us/....这一概念在所有高级语言中基本相同。
除了最后替换try块中的返回之外,异常也是如此。引发异常的finally块将替换try块中引发的返回或异常。