Does a finally block always get executed in Java?

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

    Also, although it's bad practice, if there is a return statement within the finally block, it will trump any other return from the regular block. That is, the following block would return false:

    try { return true; } finally { return false; }
    

    Same thing with throwing exceptions from the finally block.

    0 讨论(0)
  • 2020-11-21 07:36

    Also a return in finally will throw away any exception. http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html

    0 讨论(0)
  • In addition to the point about return in finally replacing a return in the try block, the same is true of an exception. A finally block that throws an exception will replace a return or exception thrown from within the try block.

    0 讨论(0)
  • 2020-11-21 07:38

    Yes It will. Only case it will not is JVM exits or crashes

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题