Try Catch时遇到return,finally还会继续执行吗

finally代码总会执行

没有异常发生的时候,在try内的代码执行结束后,执行finally。

如果发生了异常并且被catch捕获,则在执行完catch之后执行finally。

如果有异常且未被捕获,则在异常被抛给上层之前执行。

public class Test {
    public static void main(String[] args) {
        int j = test();
        System.out.println(j);
    }

    public static int test() {
        int i = 0;
        try {
            return i;
        } finally {
            i = 1;
            System.out.println("finally代码被执行");
        }
    }
}

返回结果为:

finally代码被执行
0

finally里面的代码被执行。但是,虽然给i赋值了1。但返回的值还是0。

所以,即使在try里面使用了return,依然会执行finally。但是finally无法改变返回值。

在执行的过程中, 如果try执行到return,会先将i的值保存在一个临时变量中,等到finally执行完毕之后再将保存的值取出返回。因此finally无法改变最终的返回结果

如果在 return和finally中同时遇到return会怎么样?

public class Test {
    public static void main(String[] args) {
        int j = test();
        System.out.println(j);
    }
    public static int test(){
        int i = 0;
        try{
            return i;
        }finally {
            i = 1;
            return i;
        }
    }
}

返回结果为:

1

当遇到try与finally语句中同时含有return语句,会忽略try中return

《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的情况下,会先将try中将要return的值先存到一个临时变量中,然后执行finally子句,从finally子句返回时,返回保存在临时变量中的值。

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值