面试题:try catch finally执行顺序

一、程序无异常

public class TestCatch {
	public int getCatch(String number) {
		try {
			Integer.parseInt(number);
		} catch (Exception e) {
			System.out.println("catch block");
			return 1;
		} finally {
			System.out.println("final block");
			return 2;
		}
		// return 3;
	}

	public static void main(String[] args) {
		TestCatch testCatch = new TestCatch();
		System.out.println(testCatch.getCatch("2"));
	}
}

执行结果:

final block
2

二、程序有异常

1、finally无返回值

finally无返回值,那必定try中有返回值,或者执行完try流程之后,最后写返回值。

public class TestCatch {
	public int getCatch(String number) {
		try {
			Integer.parseInt(number);
			return 3;
		} catch (Exception e) {
			System.out.println("catch block");
			return 1;
		} finally {
			System.out.println("final block");

		}
		//返回值写try里或者写在try流程外
		// return 3;
	}

	public static void main(String[] args) {
		TestCatch testCatch = new TestCatch();
		System.out.println(testCatch.getCatch(null));
	}
}

执行结果:
说明:遇到异常先走catch,所以输出了catch block,然后走了return 1.但是最终又走了finally,发现无返回值,所以又重新走return 1 将结果返回。

catch block
final block
1

2、finally有返回值

public class TestCatch {
	public int getCatch(String number) {
		try {
			Integer.parseInt(number);
			return 3;
		} catch (Exception e) {
			System.out.println("catch block");
			return 1;
		} finally {
			System.out.println("final block");
			return 3;
		}
	}

	public static void main(String[] args) {
		TestCatch testCatch = new TestCatch();
		System.out.println(testCatch.getCatch(null));
	}
}

执行结果:
说明:最终走finally有返回值,直接返回

catch block
final block
3

三:总结

代码顺序执行从try到finally,由于finally是无论如何都会执行的,所以try里的语句并不会直接返回。理解起来就是一个局部变量指向的问题,本代码测试并未使用变量,其实一个意思。

  • finally语句总会执行
  • 尽量不要在finally中使用return语句,如果使用的话,会忽略try、catch中的返回语句,也会忽略try、catch中的异常,屏蔽了错误的发生
  • finally中避免再次抛出异常,一旦finally中发生异常,代码执行将会抛出finally中的异常信息,try、catch中的异常将被忽.也就失去了try语法的效果。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值