Does a finally block always get executed in Java?

前端 未结 30 1555
逝去的感伤
逝去的感伤 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:47

    I tried the above example with slight modification-

    public static void main(final String[] args) {
        System.out.println(test());
    }
    
    public static int test() {
        int i = 0;
        try {
            i = 2;
            return i;
        } finally {
            i = 12;
            System.out.println("finally trumps return.");
        }
    }
    

    The above code outputs:

    finally trumps return.
    2

    This is because when return i; is executed i has a value 2. After this the finally block is executed where 12 is assigned to i and then System.out out is executed.

    After executing the finally block the try block returns 2, rather than returning 12, because this return statement is not executed again.

    If you will debug this code in Eclipse then you'll get a feeling that after executing System.out of finally block the return statement of try block is executed again. But this is not the case. It simply returns the value 2.

提交回复
热议问题