The finally block, if used, is placed after the try block and the catch blocks that follow it. The finally block contains code that will be run regardless of whether an exception is thrown in the try block. The general syntax is as follows:
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 possible scenarios here:
The try block runs to the end, and no exception is thrown. In this case, the finally block will be executed after the try block.
An exception was thrown in the try block, which then fell into one of the catch blocks. In this case, the finally block will be executed immediately after the catch block is executed.
An exception is thrown in the try block and there is no corresponding catch block in the method that can throw an exception. In this case, the method call ends and the exception object is passed to the method - as in the method in which try-catch-finally blocks. But, before the method ends, finally the block is executed.
Before the try block completes, it will return to wherever the method was called. But, before it returns to the calling method, the code in the finally block is still executed. So, remember that the code in the finally block will execute even if there is a return somewhere in the try block.
Update: Finally, ALWAYS is executed, regardless of what happens in the try or catch block (fail, return, exception, finish, etc.).
source share