When finally is executed?

This question already has an answer here:

  • Does finally always execute in Java? 50 answers

  • The finally block always executes when the try block exits (单击) The finally block always executes when the try block exits


    The finally block, if used, is placed after a try block and the catch blocks that follow it. The finally block contains code that will be run whether or not an exception is thrown in a try block. The general syntax looks like this:

    public void someMethod{
       Try {
       // some code
       }
    
       Catch(Exception x) {
       // some code
       }
    
       Catch(ExceptionClass y) {
       // some code
       }
    
       Finally{
       //this code will be executed whether or not an exception 
       //is thrown or caught
       }
    }
    

    There are 4 potential scenarios here:

  • The try block runs to the end, and no exception is thrown. In this scenario, the finally block will be executed after the try block.

  • An exception is thrown in the try block, which is then caught in one of the catch blocks. In this scenario, the finally block will execute right after the catch block executes.

  • An exception is thrown in the try block and there's no matching catch block in the method that can catch the exception. In this scenario, the call to the method ends, and the exception object is thrown to the enclosing method - as in the method in which the try-catch-finally blocks reside. But, before the method ends, the finally block is executed.

  • Before the try block runs to completion it returns to wherever the method was invoked. But, before it returns to the invoking method, the code in the finally block is still executed. So, remember that the code in the finally block willstill be executed even if there is a return statement somewhere in the try block.

  • Update: Finally ALWAYS gets executed, no matter what happens in the try or catch block (fail, return, exception, finish etc.).


    Yes, Finally always executes. With exception and with NO exception.

    It's the way to be sure some portion of code get always executed.

    Used for example, to dispose objects, to close opened server connections and that kind of stuff.

    Check this link from oracle:

    http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

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

    上一篇: 尝试{} finally {}用返回值构造

    下一篇: 当最后执行?