Does finally always execute in Java?

考虑到这个代码,我可以绝对确定finally块总是执行,不管什么something()是什么?

try {  
    something();  
    return success;  
}  
catch (Exception e) {   
    return failure;  
}  
finally {  
    System.out.println("i don't know if this will get printed out.");
}

Yes, finally will be called.

The only times finally won't be called are:

  • If you invoke System.exit() ;
  • If the JVM crashes first;
  • If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the try or catch block;
  • If the OS forcibly terminates the JVM process; eg "kill -9 " on UNIX.
  • If the host system dies; eg power failure, hardware error, OS panic, etcetera.

  • Example code:

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

    Output:

    finally trumps return. 
    0
    

    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.

    链接地址: http://www.djcxy.com/p/2022.html

    上一篇: 直接投射vs'as'运营商?

    下一篇: 最终总是在Java中执行?