CodeBlanks Logo Icon CodeBlanks

finally block

C# course · Beginner · Lesson 107/116

Learn cleanup code that runs even on errors with finally.

What is the finally block for?

The finally block runs no matter how the try block exits (whether or not an exception occurs). It is typically used for resource cleanup: closing files, releasing connections, or resetting flags.

For example, in try { ... } finally { CloseFile(); }, CloseFile is called under all conditions. Even if an exception is thrown and a catch block runs, finally still executes, preventing resource leaks.

Order of try/catch/finally

The order of these three blocks is: first try, then any catch blocks, and finally the optional finally. catch and finally can both be present; but neither can appear without a try.

The flow: if an exception occurs in try, the matching catch runs; then finally executes. If no exception, catch is skipped and finally still runs. Only abrupt exits like Environment.Exit may skip finally.

Resource cleanup

In real projects, the finally block is mostly used for resource cleanup. After opening a file, you want to close it even if an error occurs; after opening a database connection, you must release it no matter what.

For example, in try { OpenFile(); ReadData(); } finally { CloseFile(); }, CloseFile is called even if ReadData throws. This is a standard way to write safe code without leaking resources. Modern C# also offers the using statement for the same purpose.

Exercise Print the flow with try/finally

Inside a try block, write Console.WriteLine("Started");. Inside a finally block, write Console.WriteLine("Done");. Since there is no exception, both messages will be printed.

Show example solution
Write try { Console.WriteLine("Started"); } and finally { Console.WriteLine("Done"); }
Example solution:
using System;

class Program
{
    static void Main()
    {
        try
        {
            Console.WriteLine("Started");
        }
        finally
        {
            Console.WriteLine("Done");
        }
    }
}

Test yourself

  1. When does the finally block run?

    try { ... }
    catch { ... }
    finally { ... }
    • Only when an error occurs
    • Only when no error occurs
    • In all cases
    • Only when catch runs
    Show answer

    In all cases — Correct! finally runs in all cases, with or without an error.

  2. The finally keyword

    try { int.Parse("x"); }
    catch { }____ { Console.WriteLine("Cleanup"); }
    Show answer
    try { int.Parse("x"); }
    catch { }finally { Console.WriteLine("Cleanup"); }
  3. Match each block with its job

    try
    Risky code
    catch
    Catches errors
    finally
    Cleanup

All lessons in Beginner