在try/catch里return语句比finally语句先执行

在使用finally时想到一个问题,如果在try...catch语句中有return语句,思考它跟finally语句的执行顺序。

撸码试试:

package javaTest;

public class ReturnTest {
	
	public static final int test2(){
		try {
			 int i = 1 / 0 ;
		} catch (Exception e) {
			System.out.println("before");
			return test1();
		}finally{
			System.out.println("finally");
		}
		return 0;
	}
	public static int test1(){
		System.out.println("after");
		return 100;
	}
	public static void main(String[] args) {
		test2();
	}
}

执行结果如下:

before
after
finally

看来是return 语句比finally语句先执行。

如果return 语句换成System.exit(0);呢?再撸一撸:

package javaTest;

public class ReturnTest {
	
	public static final void test(){
		try {
			 int i = 1 / 0 ;
		} catch (Exception e) {
			System.out.println("before");
			System.exit(0);
		}finally{
			System.out.println("finally");
		}
	}
	public static void main(String[] args) {
		test();
	}
}

结果只打印before,说明finally语句在System.exit(0);正常退出时不会被执行。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值