JVM如何执行Try catch finally块 [英] how the Try catch finally block is executed by JVM

查看:217
本文介绍了JVM如何执行Try catch finally块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Java语言规范,Section§14.20.2

According to Java Language Specification, Section §14.20.2


首先执行try块,执行带有finally块的try语句。然后有一个选择:

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


  • 如果try块的执行正常完成,则执行finally
    块,然后执行有一个选择:

    • 如果finally块正常完成,则try语句正常完成。

    • 如果finally块突然完成因为S,然后try语句突然完成S

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

    If I interpret it correctly then after execution of try block finally is invoked, But how all this works and why I got the output,

    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.

    I want to know how this thing produced output 10.


    当执行try块并且遇到return语句时输出值已经被推送到堆栈,然后执行finally块

    我知道先遇到返回,然后最后块运行,因此输出为10,但
    如何jvm解释或jvm如何处理或转换try finally块?

    是jvm使用GOTO部分跳转部分转到finally部分或者堆栈已经被维护了吗?

    I know that return is encountered first then finally blocks runs so output is 10, but How jvm interpret or how the try finally block is handled or converted by jvm?
    Is that jvm uses GOTO section jump section to go to finally section or the stack is already maintained?

    推荐答案

    经过一番搜索,看到生成了什么字节码,我发现实际上没有最终似乎没有块,也没有JVM生成的跳转或goto语句。

    上面的代码翻译为(如果我正确解释字节代码,如果我错了请纠正我)

    After a little search and seeing what byte codes were generated, I found that actually there are no finally blocks as it seems and no jump or goto statements generated by JVM.
    The above code is translated something as (if I interpret byte code correctly, If I am wrong please do correct me)

    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块中更改了对象的内容,那么这些更改将反映在返回的价值也是。

    Point to Note: If 'i' would have been a reference to a mutable class object and the contents of the object were changed in the finally block, then those changes would have been reflected in the returned value too.

    这篇关于JVM如何执行Try catch finally块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆