Finally Block

Why Trust Techopedia

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.

Advertisements

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.

Advertisements

Related Terms

Margaret Rouse
Technology Specialist
Margaret Rouse
Technology Specialist

Margaret is an award-winning writer and educator known for her ability to explain complex technical topics to a non-technical business audience. Over the past twenty years, her IT definitions have been published by Que in an encyclopedia of technology terms and cited in articles in the New York Times, Time Magazine, USA Today, ZDNet, PC Magazine, and Discovery Magazine. She joined Techopedia in 2011. Margaret’s idea of ​​a fun day is to help IT and business professionals to learn to speak each other’s highly specialized languages.