The finally
clause is generally used to clean up after the code in the try
clause (e.g., close files and shut down network connections). The finally
clause is useful because it is guaranteed to be executed if any portion of the try
block is executed, regardless of how the code in the try
block completes. In fact, the only way a try
clause can exit without allowing the finally
clause to be executed is by invoking the System.exit() method, which causes the Java interpreter to stop running.
In the normal case, control reaches the end of the try
block and then proceeds to the finally
block, which performs any necessary cleanup. If control leaves the try
block because of a return, continue, or break statement, the finally
block is executed before control transfers to its new destination.
If an exception occurs in the try
block and there is an associated catch block to handle the exception, control transfers first to the catch block and then to the finally
block. If there is