按理说finally是一定执行的,但也不排除特例,比如说以下代码:
public class SystemExitAndFinally {
public static void main(String[] args)
{
try{
System.out.println("in main");
throw new Exception("Exception is thrown in main");
}
catch(Exception e) {
System.out.println(e.getMessage());
System.exit(0); }
finally {
System.out.println("in finally");
}
}
}
它的运行结果只有
in main
Exception is thrown in main
我们发现他的finally没有执行
这是因为 System.exit(status);这个方法是用来结束当前正在运行中的java虚拟机。如何status是非零参数,那么表示是非正常退出。