Home
Map
finally KeywordUse the finally keyword to ensure a block of code always runs. Finally is part of exception handling.
C#
This page was last reviewed on Dec 16, 2021.
Finally. C# code in finally blocks is always executed. In this way, the finally keyword helps ensure the correct execution of C# programs.
C# keyword info. Finally ensures a block of statements are always reached before the enclosing method is exited. It is part of the exception handling control flow.
Exception
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.
Random
And This random value is used to determine whether to throw an exception, immediately return, or do nothing.
return
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.
Console.WriteLine
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"); } } }
Unhandled Exception: System.Exception: Random = 0 at Program.Main() ... Control flow reaches finally
Random = 1 Control flow reaches finally
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).
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.
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().
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 defines the end finally 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.
Detail 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
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 16, 2021 (edit).
Home
Changes
© 2007-2024 Sam Allen.