What Does Finally Block Mean?
A finally block, in the context of C#, refers to a block of statements that are always executed, regardless of unexpected events or exceptions that may occur during an application's execution. It is used optionally with the "try/catch" block and guarantees the execution of any code that must be executed before exiting the "try" block, regardless of the success or failure of the application's execution.
The execution of a finally block is intended to release resources, such as database connections, which are usually available in limited quantities. By this mechanism, the disposal of resources occurs earlier than the garbage collector's finalization operation, thereby optimizing memory.
Techopedia Explains Finally Block
The code in the finally block can be employed to handle exceptions as soon as they occur, clean up memory allocated in the "try" block or dispose of objects holding external resources (like file handles) used in the "try" block. A finally block also facilitates the performance of housekeeping tasks like resetting a cursor to a normal state prior to the time of an exception.
In general, the code within a finally block is executed when control exits a try block as a result of normal execution, as a result of the execution of a "break", "goto", "continue" or "return" statement or due to an exception out of the try statement.
Whenever an exception occurs in the try block, control passes from the line that caused the exception to the nearest catch block (exception handler) and then to the finally block. Also, when an exception is rethrown in a catch block, control transfers to the finally block. Thus, code that follows the line where the exception occurred will be skipped.
Exceptions should not be thrown explicitly in a finally block. If an exception occurs during the execution of a finally block, any code after the point where the exception is thrown will not execute, and the exception will propagate to the outer enclosing try block. If the finally block is already handling another exception, this results in termination of the processing of the current exception.
Care should be taken not to explicitly transfer execution into or out of a finally block as this is not a valid transfer.