Does a finally block always get executed in Java?

前端 未结 30 1632
逝去的感伤
逝去的感伤 2020-11-21 07:24

Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?

try         


        
30条回答
  •  忘掉有多难
    2020-11-21 07:52

    This is because you assigned the value of i as 12, but did not return the value of i to the function. The correct code is as follows:

    public static int test() {
        int i = 0;
        try {
            return i;
        } finally {
            i = 12;
            System.out.println("finally trumps return.");
            return i;
        }
    }
    

提交回复
热议问题