try catch finally return 执行顺序,高频面试题,注意事项

public class ClassB {
	public static String test(int i) {
		int num = 10;
		try {
			num = num / i;
			return "success - " + num;
		} catch (Exception e) {
			num = num + 50;
			return "fail - " + num;
		} finally {
			num = num + 100;
			System.out.println("finally - " + num);
		}
	}

	public static void main(String[] args) {
		System.out.println(ClassB.test(5));
		System.out.println("--------");
		System.out.println(ClassB.test(0));
	}
}

这是一道高频面试题,面试者通常喜欢考验的try,catch,finally的执行顺序,以及之变化对下一步的影响

这里肯定的是,try先执行,catch在遇到异常后执行,finally总会执行,在finally执行完

注意的有这么几点

1.try中值变化,会传递到catch,finally,如果没有遇到一场,return里的值变化也会影响到finally

2.catch中值变化,也会影响到fianlly,return里值变化也会影响到finally

3.finally中之值变化,不会影响到try和catch

目前的执行结果是:

finally - 102
success - 2
--------
finally - 160
fail - 60

如果把代码改成如下,再return里加上自增

public class ClassB {
	public static String test(int i) {
		int num = 10;
		try {
			num = num / i;
			return "success - " + ++num;
		} catch (Exception e) {
			num = num + 50;
			return "fail - " + ++num;
		} finally {
			num = num + 100;
			System.out.println("finally - " + ++num);
		}
	}

	public static void main(String[] args) {
		System.out.println(ClassB.test(5));
		System.out.println("--------");
		System.out.println(ClassB.test(0));
	}
}

这个时候,try再没有遇到异常之前,return中的++num会自增1再传导到finally

catch中return的++num也会自增1传导到finally

而finally的值++num是不会传导到try和catch中

执行结果如下:

finally - 104
success - 3
--------
finally - 162
fail - 61

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值