0
0
CsharpHow-ToBeginner · 3 min read

How to Use finally in C#: Syntax and Examples

In C#, the finally block is used after try and optional catch blocks to run code that must execute regardless of exceptions. It is ideal for cleanup tasks like closing files or releasing resources, and it always runs whether an exception occurs or not.
📐

Syntax

The finally block follows try and optional catch blocks. It contains code that always runs after the try block finishes, whether an exception was thrown or caught.

  • try: Code that might cause an exception.
  • catch: Code to handle exceptions (optional).
  • finally: Code that always runs, used for cleanup.
csharp
try
{
    // Code that may throw an exception
}
catch (Exception ex)
{
    // Code to handle the exception
}
finally
{
    // Code that always runs
}
💻

Example

This example shows opening a file, reading from it, and ensuring the file is closed no matter what happens. The finally block closes the file even if an exception occurs.

csharp
using System;
using System.IO;

class Program
{
    static void Main()
    {
        StreamReader file = null;
        try
        {
            file = new StreamReader("example.txt");
            string content = file.ReadToEnd();
            Console.WriteLine("File content read successfully.");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("File not found.");
        }
        finally
        {
            if (file != null)
            {
                file.Close();
                Console.WriteLine("File closed in finally block.");
            }
        }
    }
}
Output
File not found. File closed in finally block.
⚠️

Common Pitfalls

One common mistake is to put code that might throw exceptions inside the finally block, which can hide the original exception or cause unexpected crashes. Also, finally should not be used to return values because it runs after return statements, which can confuse the flow.

Always keep finally blocks simple and focused on cleanup.

csharp
try
{
    Console.WriteLine("In try block");
    return;
}
finally
{
    Console.WriteLine("In finally block");
    // Avoid throwing exceptions here
}
Output
In try block In finally block
📊

Quick Reference

  • finally always runs after try/catch blocks.
  • Use it for cleanup like closing files or releasing resources.
  • It runs even if there is a return or an exception.
  • Do not throw exceptions inside finally.

Key Takeaways

Use finally to run code that must execute regardless of exceptions.
Place cleanup code like closing files or releasing resources inside finally.
Avoid throwing exceptions or returning values inside finally blocks.
finally runs even if the try block returns or throws an exception.