Finally Block

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.


Related Terms

Latest DevOps Terms

Related Reading

Margaret Rouse

Margaret Rouse is an award-winning technical writer and teacher known for her ability to explain complex technical subjects to a non-technical, business audience. Over the past twenty years her explanations have appeared on TechTarget websites and she's been cited as an authority in articles by the New York Times, Time Magazine, USA Today, ZDNet, PC Magazine and Discovery Magazine.Margaret's idea of a fun day is helping IT and business professionals learn to speak each other’s highly specialized languages. If you have a suggestion for a new definition or how to improve a technical explanation, please email Margaret or contact her…