Java 的 catch 块里有 return 语句执行时,finally 块里的语句会怎么执行?

遇到个很有意思的问题,Java 的 catch 块里有 return 语句执行时,finally 块里的语句会执行吗?执行顺序是怎样的?
虽然平时很少这样写,但这是个值得思考的问题,这篇博客就来求证一下。

场景一:return x,返回只有一个引用

public class Test {

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

    public static int test() {
        int x = 0;
        try {
            throw new Exception();
        } catch (Exception e) {
            return x;
        } finally {
            System.out.println("执行finally块");
        }
    }
}

执行上述代码,得到结果:

执行finally0

可以看出来先执行的 finally 块的语句,再返回到调用者。

场景二:return x = x + 1,返回的是一个计算赋值语句

对上述代码稍做修改:

public class Test {

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

    public static int test() {
        int x = 0;
        try {
            throw new Exception();
        } catch (Exception e) {
            return x = x + 1;
        } finally {
            System.out.println(x);
        }
    }
}

执行上述代码,得到结果:

1
1

说明先执行的 return 语句 x = x + 1,再执行的finally 块。

场景三:如果 finally 块中有对返回值 x 的修改,会返回给调用者吗?

对上述代码稍做修改:

public class Test {

    public static void main(String[] args) {
        int back = Test.test();
        System.out.println("调用者中 x = " + back);
    }

    public static int test() {
        int x = 0;
        try {
            throw new Exception();
        } catch (Exception e) {
            return x = x + 1;
        } finally {
            x = x - 1;
            System.out.println("finally中 x = " + x);
        }
    }
}

执行上述代码,结果如下:

finally中 x = 0
调用者中 x = 1

这下有点意思了,finally 块中的 x = x - 1虽然执行了,但是并没有影响返回值。这说明在 return 那已经确定并保存了返回值,finally 块里的语句是改变了 x 的值,但并没有改变要返回的值。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值