Does a finally block always get executed in Java?

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

    finally is always executed and before returning x's (calculated) value.

    System.out.println(foo());
    
    ....
    
    int foo(){
        int x = 2;
        try{
            return x++;
        } finally{
            System.out.println(x);
        }
    }
    

    Output:

    3
    2
    

提交回复
热议问题