考虑到此代码,我是否可以绝对确定该finally块始终执行,无论它是什么something()?
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将在执行try或catch代码块后调用。
try
catch
唯一finally不会被调用的时间是:
System.exit()
Runtime.getRuntime().halt(exitStatus)
kill -9 <pid>
示例代码:
public static void main(String[] args) { System.out.println(Test.test()); } public static int test() { try { return 0; } finally { System.out.println("finally trumps return."); } }
输出:
finally trumps return. 0