finally出现了return情况分析以及finally对返回值影响情况分析

1finally 出现了 return
先问问自己,下面的题目输出什么?
由于 finally 中的 ireturn 被插入了所有可能的流程,因此返回结果肯定以 finally 的为准
至于字节码中第 2 行,似乎没啥用,且留个伏笔,看下个例子
跟上例中的 finally 相比,发现没有 athrow 了,这告诉我们:如果在 finally 中出现了 return,会
吞掉异常😱😱😱,可以试一下下面的代码
public class Demo3_12_2 {
  public static void main(String[] args) {
    int result = test();
    System.out.println(result);
 }
  public static int test() {
    try {
      return 10;
   } finally {
      return 20;
   }
 }
}

 public static int test();
  descriptor: ()I
  flags: ACC_PUBLIC, ACC_STATIC
  Code:
   stack=1, locals=2, args_size=0
    0: bipush     10   // <- 10 放入栈顶
    2: istore_0       // 10 -> slot 0 (从栈顶移除了)
    3: bipush     20   // <- 20 放入栈顶
    5: ireturn       // 返回栈顶 int(20)
    6: astore_1       // catch any -> slot 1
    7: bipush     20   // <- 20 放入栈顶
    9: ireturn       // 返回栈顶 int(20)
   Exception table:
    from   to  target type
      0   3   6  any
   LineNumberTable: ...
   StackMapTable: ...

由于 finally 中的 ireturn 被插入了所有可能的流程,因此返回结果肯定以 finally 的为准
至于字节码中第 2 行,似乎没啥用,且留个伏笔,看下个例子
跟上例中的 finally 相比,发现没有 athrow 了,这告诉我们:如果在 finally 中出现了 return,会
吞掉异常😱😱😱,可以试一下下面的代码

public class Demo3_12_1 {
  public static void main(String[] args) {
    int result = test();
    System.out.println(result);
 }
 
  public static int test() {
    try {
      int i = 1/0;
      return 10;
   } finally {
      return 20;
   }
 }
}
2finally 对返回值影响

public class Demo3_12_2 {
  public static void main(String[] args) {
    int result = test();
    System.out.println(result);
 }
  public static int test() {
    int i = 10;
    try {
      return i;
   } finally {
      i = 20;
   }
 }
}
 public static int test();
  descriptor: ()I
  flags: ACC_PUBLIC, ACC_STATIC
  Code:
   stack=1, locals=3, args_size=0
    0: bipush     10   // <- 10 放入栈顶
    2: istore_0       // 10 -> i
    3: iload_0       // <- i(10)
    4: istore_1       // 10 -> slot 1,暂存至 slot 1,目的是为了固定返回值
    5: bipush     20   // <- 20 放入栈顶
    7: istore_0       // 20 -> i
    8: iload_1       // <- slot 1(10) 载入 slot 1 暂存的值
    9: ireturn       // 返回栈顶的 int(10)
    10: astore_2
    11: bipush     20
    13: istore_0
    14: aload_2
    15: athrow
   Exception table:
    from   to  target type
      3   5   10  any
   LineNumberTable: ...
   LocalVariableTable:
    Start  Length  Slot  Name  Signature
      3    13   0   i  I
   StackMapTable: ...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值