zoukankan      html  css  js  c++  java
  • Java中Return和Finally运行顺序的实现

    以下这段代码的运行结果是如何的呢?

    1. publc int test(){  
    2.     int x;  
    3.     try{  
    4.         x = 1;  
    5.         return x;  
    6.     }catch(Exception e){  
    7.         x = 2;  
    8.         return x;  
    9.     }finally{  
    10.         x = 3;  
    11.     }  
    12. }  

    相信对Java比較熟悉的朋友立即会说出正确答案:正常返回1。异常返回2。

    我第一次看到这段代码时,对于finally里面的x=3产生了疑惑,不确定最后返回的x是否变成了3。直到从《深入理解Java虚拟机》里面找到了这段代码的字节码,才明确其执行机制。

    以下是上面这段Java代码的字节码:

    1. public int test();  
    2.   Code:  
    3.    Stack=1, Locals=5, Args_size=1  
    4.    0:   iconst_1   //将1写入栈顶  
    5.    1:   istore_1   //将栈顶值(1)写入第2个int型本地变量  
    6.    2:   iload_1    //将第2<span style="font-family: Arial, Helvetica, sans-serif;">个int型本地变量load到栈顶(Return语句的開始)</span>  
    7.    3:   istore  4  //保存栈顶值到<span style="font-family: Arial, Helvetica, sans-serif;">第4个int型本地变量</span>,此时x=1  
    8.    5:   iconst_3   //将3写入栈顶(Finally開始)  
    9.    6:   istore_1   //将3写入<span style="font-family: Arial, Helvetica, sans-serif;">第2个int型本地变量</span>  
    10.    7:   iload   4  //将<span style="font-family: Arial, Helvetica, sans-serif;">第4个int型本地变量的值laod到栈顶</span>  
    11.    9:   ireturn    //返回栈顶的值  
    12.    10:  astore_2  
    13.    11:  iconst_2  
    14.    12:  istore_1  
    15.    13:  iload_1  
    16.    14:  istore  4  
    17.    16:  iconst_3  
    18.    17:  istore_1  
    19.    18:  iload   4  
    20.    20:  ireturn  
    21.    21:  astore_3  
    22.    22:  iconst_3  
    23.    23:  istore_1  
    24.    24:  aload_3  
    25.    25:  athrow  
    从上面的字节码能够看出,Return语句被分为两部分:iload 4和ireturn,在store和load之间插入的是finally代码。x的值首先被存放到一个指定的位置,再运行finally语句。这时finally中的代码已无法影响返回值了。
  • 相关阅读:
    LeetCode 326. Power of Three
    LeetCode 324. Wiggle Sort II
    LeetCode 322. Coin Change
    LeetCode 321. Create Maximum Number
    LeetCode 319. Bulb Switcher
    LeetCode 318. Maximum Product of Word Lengths
    LeetCode 310. Minimum Height Trees (DFS)
    个人站点大开发!--起始篇
    LeetCode 313. Super Ugly Number
    LeetCode 309. Best Time to Buy and Sell Stock with Cooldown (DP)
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5219544.html
Copyright © 2011-2022 走看看