<span style="font-size:18px;">public class TryCatchFinally
{
public static void main(String[] args)
{
System.out.println("Hello World!");
System.out.println(fun1());
}
public static int fun(){
int i = 10;
try{
//new Foo();
i = 1 / 1;
System.out.println("try");
System.exit(0);
//return i++;
}catch(Exception ex){
System.out.println("Exception");
i++;
return i;
}finally{
System.out.println("Finally");
i++;
return 1;
}
}
public static void fun1(){
try{
new Foo();
}catch(Exception ex){
System.out.println("Exception");
return ;
}finally{
System.out.println("Finally");
}
}
static class Foo
{
public Foo(){
new Foo();
}
}
}</span>
通常,try---catch---finally块,finally一定在最后执行一次。那么这是不是一定的呢?
观察上述代码,main执行fun1()时,会出现什么情况?
运行就会发现什么也不输出,因为栈溢出了,当这个错误发生时,程序已经无法执行,更别说执行finally了。
观察fun()函数,有一个System.exit(0);
这个函数是什么意思?
System是一个Java类,调用exit(0)方法终止虚拟机也就是退出你的Java程序,括号里面的是参数,进程结束的返回值。
所以通过上面可以知道,exit(0)会终止虚拟机,虚拟机都终止了,谁还管finally了,是吧!