Does a finally block always get executed in Java?

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

    Here's an elaboration of Kevin's answer. It's important to know that the expression to be returned is evaluated before finally, even if it is returned after.

    public static void main(String[] args) {
        System.out.println(Test.test());
    }
    
    public static int printX() {
        System.out.println("X");
        return 0;
    }
    
    public static int test() {
        try {
            return printX();
        }
        finally {
            System.out.println("finally trumps return... sort of");
        }
    }
    

    Output:

    X
    finally trumps return... sort of
    0
    

提交回复
热议问题