TheDeveloperBlog.com


C# Finally

Finally. Code in finally blocks is always executed. Finally provides a construct for ensuring the correct execution of programs. It ensures a block of statements are always reached before the enclosing method is exited.


Example. This program shows how the finally clause is part of the control flow in programs. In this program, a random number is generated. This value is used to determine whether to throw an exception, immediately return, or do nothing.

RandomReturn

Info: In each of the three cases, the finally block is reached immediately after processing completes.

And: In this way, the finally block can be used to ensure that some logic is always executed before the method is exited.

C# program that uses finally and control flows

using System;

class Program
{
    static void Main()
    {
	try
	{
	    // Acquire random integer for use in control flow.
	    // ... If the number is 0, an error occurs.
	    // ... If 1, the method returns.
	    // ... Otherwise, fall through to end.
	    int random = new Random().Next(0, 3); // 0, 1, 2
	    if (random == 0)
	    {
		throw new Exception("Random = 0");
	    }
	    if (random == 1)
	    {
		Console.WriteLine("Random = 1");
		return;
	    }
	    Console.WriteLine("Random = 2");
	}
	finally
	{
	    // This statement is executed before Main exits.
	    // ... It is reached when an exception is thrown.
	    // ... It is reached after the return.
	    // ... It is reached in other cases.
	    Console.WriteLine("Control flow reaches finally");
	}
    }
}

Possible output #1

Unhandled Exception: System.Exception: Random = 0
   at Program.Main() ...
Control flow reaches finally

Possible output #2

Random = 1
Control flow reaches finally

Possible output #3

Random = 2
Control flow reaches finally

Control flow and paths. The program introduces the Main entry point method, where control flow begins. Next, a Random number is generated and this is used to randomly throw an exception, return or continue.

So: In all cases, the string "Control flow reaches finally" is printed to the console window.

Console

Leave instruction. An important instruction is the "leave" instruction, which is generated whenever the try block is exited. Each method contains an exception-handling section that indicates where the finally handler is defined.

Then: When the leave instruction is encountered, that section is used to direct the flow of control.

Also: The IL also defines the endfinally instruction. This is an implementation detail.


Specification. In the C# specification, we encounter many points regarding the finally block and how it conflicts with language constructs. For example, the goto statement has many restrictions and you cannot go to a label outside of the finally block.

Goto

And: The specification details these restrictions at length. This article only touches on these points.

Error: If you use a goto in a finally block, you will get an error: "Control cannot leave the body of a finally clause."


Console program. One use for the finally clause in C# programs is to wrap the body of the Main method with a try-finally construct. Then in the finally clause, you can print a message that indicates that the program is finished processing.

Tip: For console programs you can put a Console.ReadLine in the finally clause, providing an exit prompt to better inform the user.

Console.ReadLine

Catch. How does the catch block relate to the finally block? The two constructs are separate. The catch block is for handling errors. And the finally block can be used to perform important resource management tasks such as closing files.

Tip: The finally block does not involve an error. But it relies on the same alternate control flow mechanism as catch.

Catch

Summary. A finally block is a way to ensure a piece of logic is executed before the method is exited. The finally construct is separate conceptually from the catch block. But it uses the exception-handling control flow mechanism.

Thus: The finally block is used to free certain system resources in libraries, or for custom cleanup mechanisms or messages.