JAVA中 try - finally中都存在return的效果

如下是运行的结果

public class TryTest {
    public static void main(String[] args) {
        System.out.println(returnNum());
    }

    public static Integer returnNum(){
        try{
            return 2;
        }finally {
            return 3;
        }
    }
}

返回的结果是3;

public class TryTest {
    public static void main(String[] args) {
        System.out.println(returnNum());
    }

    public static Integer returnNum(){
        try{
            return 2;
        }finally {
            System.out.println("hahahh");
        }
    }
}

返回的结果是 2;

解释说明:
官方的jvm规范说明如下:

If the try clause executes a return, the compiled code does the following:

Saves the return value (if any) in a local variable.
Executes a jsr to the code for the finally clause.
Upon return from the finally clause, returns the value saved in the local variable.
如果try语句里有return,那么代码的行为如下:
1.如果有返回值,就把返回值保存到局部变量中
2.执行jsr指令跳到finally语句里执行
3.执行完finally语句后,返回之前保存在局部变量表里的值

个人解释
也就是先执行try中的语句-> 执行计算return的值存储到局部变量表中 ->跳转到finally ->返回try中的return,即try中return存储在临时变量表中的值,但是如果finally中存在return就直接终止了程序,不会在去返回try中存储在临时变量表中的值

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值