当try语句块中存在return语句时,还会执行finally吗

其实在java官方文档中有描述,当try语句块执行结束后是一定会执行finally的。因此一般情况下在finally中做一些关闭流的操作,因为try中的return,break,continue等都影响不到它,那么到底是怎么执行return又执行finally的呢,看代码:

public class Test01 {
	public static void main(String[] args) {
		int a = 0;
		System.out.println(add(a));
	}
	public static int add(int b) {
		try {
			b++;
			return b;
		}catch(Exception e) {
			System.out.println(" ");
		}finally {
			b++;
//			return b;
		}
		return b;
	}
}

在这里插入图片描述
为什么输出结果是1而不是2呢,JVM规范是这样解释的

If the try clause executes a return, the compiled code does the following:
1.Saves the return value (if any) in a local variable.
2.Executes a jsr to the code for the finally clause.
3.Upon return from the finally clause, returns the value saved in the local variable.

就是说在try中存在return语句的情况下会先将返回值存到一个本地变量中,接下来再去执行finally代码块,虽然又做了一次b++,值变成了2,可最后返回的是存在本地变量的值 也就是b=1。

不过需要注意的是,如果是在finally中写了return语句,那么返回结果就是2了,因为规范中规定当try和finally中同时存在return会自动忽略try语句块中的而去使用finally中的return。

不过在finally中使用return也会有问题,这样会造成程序提前结束,具体的可以参考这个链接:在finally中写return会怎么样

总结:

  1. 执行try语句块后一定会执行finally。
  2. 当try和finally中同时存在return会忽略try的return而去执行finally的return。
  3. 不要在finally中写return语句。

参考自:https://www.cnblogs.com/xichji/p/12009222.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值