如果 System.exit(0) 被调用 finally 块 will not 执行( since the Java VM exits when that statement is called )
it will 在调用 return 语句时执行( since the Java VM does not exit when that statement is called ) .
你可以用我写的一些代码来确认:
public class TryExample {
public static void main(String[] args)
{
try {
int[] i = {1, 2, 3};
int x = i[3];//Change to 2 to see "return" result
return;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("caught");
System.exit(0);
} finally {
System.out.println("finally");
}
}
}
3 回答
在
return
的情况下,是的 . 如果你想要血腥细节,它们在JLS section 14.20.2中指定 .(请注意,在JLS术语中,
return
算作突然终止 . 但这并不重要,因为当您仔细分析规范时,您将看到finally
被执行以进行正常和突然终止 . )在
System.exit()
的情况下,否 . 对exit
方法的调用永远不会返回,也不会抛出异常 . 因此,线程的"enclosing"finally
子句永远不会被执行 .(在JLS的说法中,
exit()
调用不会使用任何CPU时间 . 与JVM关闭相关的所有活动都发生在其他线程上 . )根据the tutorials from Oracle:
这句话似乎意味着:
如果
System.exit(0)
被调用finally
块 will not 执行( since the Java VM exits when that statement is called )it will 在调用
return
语句时执行( since the Java VM does not exit when that statement is called ) .你可以用我写的一些代码来确认:
这里,当在
try
块中调用return
时,"finally"仍然输出到终端,但是当在catch
块中调用System.exit(0)
时,它不是 .不,它不会,当try-catch没有正常完成时,最后阻止不会被执行 .
这是JLS或它和州:
同样适用于 catch block
因为你正在调用
System.exit
来终止try block
中的程序,所以try-catch没有正常完成,因此finally block
不会被执行 .对于
return statement
,try-catch确实正常完成,因为你没有阻塞try block
(例如无限循环,休眠线程,终止程序等),因此从方法返回后执行finally block
.