This question already has answers here:
Why does changing the returned variable in a finally block not change the return value?
                                
                                    (7个答案)
                                
                        
                4个月前关闭。
            
        

我已经看到了这种行为的解释,因为它通常是finally块中的不可变String,但是我不明白为什么int原语会以这种方式表现。

“ i”不按值作为方法中的参数传递。该方法直接设置i类变量。这很明显,因为在方法完成后打印时i的值会更改。

也很清楚,因为在try块中的打印首先打印,所以在try块中的return语句之前已对其进行了更改。

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块总是在“返回”并“抛出”异常之后运行,您的代码与:

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;
    }


}

09-28 00:06