gpt4 book ai didi

Java try..catch 和finally

转载 作者:行者123 更新时间:2023-12-01 06:53:36 25 4
gpt4 key购买 nike

我有以下代码:

public class test3    
{
public static void main(String a[])
{
System.out.println("In main");
System.out.println(new Demo(0).devide());
}
}
class Demo
{
int x;
Demo(int x)
{
this.x=x;
}
public int devide()
{
try
{
return x/x;
}
catch(Exception e)
{
System.out.println(e);
return 4;

}
finally
{
System.out.println("In finally");
return 1;
}
}
}

在上面的代码中,我期望输出为 4,但生成的输出是:

In main
java.lang.ArithmeticException: / by zero
In finally
1

所以它返回1

最佳答案

Finally 始终在退出 try/catch block 之前调用,即使 catch 返回也是如此。实际上,finally 中的 return 先于 catch 中的返回,并且 catch 中的返回永远不会发生。请参阅here了解详细信息和解释。

基本上,它可以归结为转换为字节码的方式。 finally 中的代码被视为“子过程”,并且在每个退出点,在离开 try/catch block 之前,都会有一个 jsr跳转执行到finally中的代码。由于子过程跳转不是真正的过程调用,finally 中的 return 禁止从子过程返回到它进入的位置,因此原来的 return 永远不会被执行。

divide() 粗略翻译为字节码可能如下所示:

    aload_0
getfield // x
dup
idiv
istore_1
jsr // to finally block
iload_1
ireturn

// catch
bipush 4
istore_1
jsr // to finally block
iload_1
ireturn

// finally
astore_2 // save the return address
bipush 1
ireturn
ret 2 // dead code

在这里我们可以清楚地看到为什么catch中的return从未被执行。

关于Java try..catch 和finally,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18652420/

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