gpt4 book ai didi

Java finally block 更改类变量的值,但不更改 Try block 中的 return 语句

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

我已经看到这种行为被解释了,因为它通常是finally block 中的不可变字符串,但我不明白为什么int原语会这样表现。

“i”不作为方法中的参数按值传递。该方法是直接设置i类变量。这是显而易见的,因为在方法完成后打印时 i 的值发生了变化。

很明显,它在 try block 中的 return 语句之前已被更改,因为 finally block 中的打印首先打印。

public class Test {
static int i = 0;
public static void main(String[] args) {

System.out.println("Try Block returns: " + methodReturningValue());
System.out.println("Value of i after method execution is " + i);
}


static int methodReturningValue()
{


try
{
i = 1;
System.out.println("try block is about to return with an i value of: "+ i);
return i;
}
catch (Exception e)
{
i = 2;
return i;
}
finally
{
i = 3;
System.out.println("Finally block: i has been changed to 3");
}
}


}

输出:

try block is about to return with an i value of: 1
Finally block: i has been changed to 3
Try Block returns: 1
Value of i after method execution is 3

最佳答案

是的,finally block 总是在“返回”和“抛出”异常之后运行,您的代码与:

public class Test {
static int i = 0;
public static void main(String[] args) {

System.out.println(methodReturningValue());
System.out.println(i);
}


static int methodReturningValue()
{

int answer = 0;
try
{
i = 1;
answer = i;
}
catch (Exception e)
{
i = 2;
answer = i;
}
i = 3;
System.out.println("i=3");
return answer;
}


}

关于Java finally block 更改类变量的值,但不更改 Try block 中的 return 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59451148/

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