gpt4 book ai didi

java - JVM 如何执行 Try catch finally block

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:27:43 24 4
gpt4 key购买 nike

根据 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 block 之后最终会被调用,但是这一切是如何工作的以及为什么我得到了输出,

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

我知道首先遇到 return 然后 finally block 运行所以输出是 10,但是jvm 如何解释或 try finally block 如何被 jvm 处理或转换?
是jvm使用GOTO段跳转段跳转到finally段还是栈已经维护好?

最佳答案

稍微搜索一下,看看生成了什么字节码,我发现实际上并没有像看起来那样的finally block ,也没有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 block 中被更改,那么那些更改也会反射(reflect)在返回值中。

关于java - JVM 如何执行 Try catch finally block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19538999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com