0

鉴于 java 中的以下 try/catch 块:

try{
  return;
}
catch(SomeException e){
  System.out.println(e);
}
finally{
  System.out.println("This is the finally block");
}

并根据这篇文章:“ finally 总是在 Java 中执行吗? ”我可以看到程序的输出将是 'This is the finally 块'。但是,我无法弄清楚这是怎么可能的,因为 print 语句之前有一个 return ...

我怀疑这种行为与线程有关,但我不确定。请赐教。谢谢你。

4

3 回答 3

4

finallyreturn在语句之前执行。finally因为除非 JVM 崩溃或被System.exit()调用,否则将始终执行java 规则。

Java 语言规范明确提到了 finally 在不同条件下的执行:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2

于 2013-11-11T05:03:11.283 回答
0

六月是正确的。我还想注意从 finally 块中抛出异常,它们会增加其他发生的异常。例如(有点愚蠢的例子,但它说明了这一点):

boolean ok = false;
try {
   // code that might throw a SQLException
   ok = true;
   return;
}
catch (SQLException e) {
   log.error(e);
   throw e;
}
finally {
   if (!ok) {
      throw new RuntimeException("Not ok");
   }
}

在这种情况下,即使捕获并重新抛出 SQLException,最终也会在此处抛出 RuntimeException,它将“屏蔽”或覆盖 SQLException。调用者将收到 RuntimeException 而不是 SQLException。

于 2013-11-11T05:14:56.847 回答
0

return语句对finally块的执行没有影响。finally不执行块的唯一方法是JVM在执行块之前崩溃/退出finally。检查此链接了解更多信息。所以,如果你的代码被替换为

try{
  System.exit(0);
}
catch(SomeException e){
  System.out.println(e);
}
finally{
  System.out.println("This is the finally block");
}

finally块不会执行

于 2013-11-11T05:08:48.857 回答