try---catch--finally,finally是否一定执行?

本文深入探讨Java中try-catch-finally语句的行为,特别是System.exit(0)和递归构造函数导致的栈溢出对finally块的影响。通过具体代码示例解释了不同情况下finally块的执行情况。

<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了,是吧!




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值