加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – JVM如何执行Try catch finally块

发布时间:2020-12-15 04:14:45 所属栏目:Java 来源:网络整理
导读:根据 Java语言规范,Section §14.20.2 A try statement with a finally block is executed by first executing the try block. Then there is a choice: If execution of the try block completes normally,then the finally block is executed,and then the
根据 Java语言规范,Section §14.20.2

A try statement with a finally block is executed by first executing the try block. Then there is a choice:

  • If execution of the try block completes normally,then the finally
    block is executed,and then there is a choice:

    • If the finally block completes normally,then the try statement completes normally.
    • If the finally block completes abruptly for reason S,then the try statement completes abruptly for reason S

如果我正确解释它然后在执行try块finally之后调用,但是这一切是如何工作的以及为什么我得到了输出,

public static int TestTryFinallyBlock()  
{
    int  i =0;
    try 
    {
        i= 10; //Perform some more operation
        return i;
    }       
    finally
    {
        i = 40; 
    }
}

public static void main( String[] args )
{
    int i1 = TestTryFinallyBlock(); //Here the output was 10 not 40
}

我想知道这个东西是如何产生输出10的.

Is that when try block is executed and return statement is encountered the output value is already pushed to stack,and then the finally block is executed

我知道首先遇到返回然后最后阻塞运行所以输出是10,但是
如何jvm解释或jvm如何处理或转换try finally块?
是jvm使用GOTO部分跳转部分到最后部分还是已经保持堆栈?

解决方法

经过一点点搜索并看到生成了什么字节码后,我发现实际上没有看起来没有finally块,也没有JVM生成的跳转或goto语句.
上面的代码被翻译为(如果我正确解释字节代码,如果我错了请请纠正我)

public static int TestTryFinallyBlock()  
{
  int returnValue; //A temporary return variable
  try
  {
     int  i = 0;     
     i = 10; 
     returnValue = i; 
     i = 40; 
     return returnValue;    
  }
  catch (RuntimeException e)
  {
       i = 40; //finally section code id copied here too
       throw e;
  }
}

注意:如果’i’是对可变类对象的引用,并且在finally块中更改了对象的内容,那么这些更改也会反映在返回的值中.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读