C# finally KeywordUse the finally keyword to ensure a block of code always runs. Finally is part of exception handling.
dot net perls

Finally. Code in finally blocks is always executed. In this way, the finally keyword helps ensure the correct execution of C# programs.

This keyword ensures a block of statements are always reached before the enclosing method is exited. It is part of the exception handling control flow.


An example. This program shows how the finally clause is part of the control flow in programs. In this program, a random number is generated.

And This random value is used to determine whether to throw an exception, immediately return, or do nothing.


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

Thus The finally block can be used to ensure that some logic is always executed before the method is exited.

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


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

Finally, syntax error. A try block must come before finally. We cannot put a finally in a block all by itself (a prelude part, the "try" is always first).

C# program that shows finally syntax error
class Program { static void Main() { // Try must come before finally. finally { } } }
Error CS1003 Syntax error, 'try' expected Error CS1514 { expected Error CS1513 } expected

Finally, syntax 2. We cannot place 2 finally blocks in an exception handling construct. Unlike "try" only 1 finally is allowed—a syntax error is reported if 2 finally blocks are used.

C# program that shows try expected error
class Program { static void Main() { // Only one finally is allowed. try { string value = "HELLO"; } finally { } finally { } } }
Error CS1003 Syntax error, 'try' expected Error CS1514 { expected Error CS1513 } expected

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 Additional flags can be used to report status messages in finally. Or multiple blocks can be placed in Main().

C# program that uses try, finally in console
using System; class Program { static void Main() { try { Console.WriteLine("Start"); // Perform important computations in try block. string temp = "x"; for (int i = 0; i < 1000; i++) { temp += "x"; } } finally { // Notify user when program is done. Console.WriteLine("Finished"); } } }
Start Finished

Leave instruction. A C# program is compiled to an intermediate language. An important instruction is the "leave" instruction, which is generated whenever the try block is exited.

Info 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.

Catch. How does the catch block relate to the finally block? The two constructs are separate. The catch block is for handling errors.

Meanwhile 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.


A 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.

Final notes. Finally uses the exception-handling control flow mechanism. The finally block is used to free system resources in libraries, or for cleanup mechanisms or messages.

© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.