skip to content

In C#, what does a `finally` block guarantee, and when does it not run or end up hiding the original exception?

level: seniorimportance: should knowfreq 48%

answer

  1. every way out of try
  2. termination that skips unwinding
  3. no return out of finally
  4. a second exception wins

basics

~20 s

A finally block runs whenever control leaves its try block: normal exit, return, break, continue, goto, or an exception that something catches. Environment.FailFast, Environment.Exit, a stack overflow or a killed process skip it, and an exception thrown inside finally replaces the original.

solid answer

~40 s

`finally` runs on every exit path from the `try` block: falling off the end, `return`, `break`, `continue`, `goto`, and an exception propagating to a handler, including one thrown by a catch block of the same statement. Control cannot leave a `finally` body with `return` or a jump (CS0157). It does not run when the process ends without unwinding: `Environment.FailFast`, `Environment.Exit` called from inside the `try`, a stack overflow, which the runtime cannot recover from, or a process killed from outside. For an exception nothing catches, the docs leave unwinding to the runtime, so cleanup that must happen should not depend on it. The subtle failure is a `finally` that throws: its exception replaces the one already in flight, so the caller sees the cleanup error and the real cause is lost.

code

csharp · 21 lines
csharp
try
{
    SettleBatch();
}
catch (Exception ex)
{
    Console.WriteLine($"caller sees: {ex.GetType().Name}: {ex.Message}");
}

static void SettleBatch()
{
    try
    {
        throw new InvalidOperationException("item INV-7 declined");
    }
    finally
    {
        Console.WriteLine("finally: closing the audit file");
        throw new IOException("audit file already closed");
    }
}

go deeper

for a junior

Recall that finally runs on normal exit, on return and when an exception leaves the try block, and that it holds cleanup code.

for a middle

List the jump statements that trigger it, explain CS0157 and the order of a return value versus finally, and mention that a throwing catch block still gets finally.

for a senior

Name the cases where finally does not run (FailFast, Exit, stack overflow, a killed process) and show the masked-exception bug with CA2219 and its fix.

for a principal

Separate cleanup from guarantees: a finally block is not a durability mechanism, so anything that must survive a crash needs its own design.

## What finally is for A `finally` block holds cleanup that must happen however the `try` block ends: releasing a lock flag, resetting state, closing something that has no `IDisposable` wrapper. (For types that implement `IDisposable`, a `using` statement generates the `try`/`finally` for you; disposal has its own material.) The promise is about **leaving the `try` block**, not about the program continuing. ## Every way out of the try block runs it The `finally` block runs when control leaves the `try` block by: - **Normal completion**, falling off the end of the block. - **A jump statement**: `return`, `break`, `continue` or `goto`. With `return value;`, the value is computed first, then `finally` runs, then the method returns. - **An exception** that propagates out of the `try` block to a handler, in this method or further up the stack. - **An exception from a catch block** of the same `try-catch-finally` statement: the docs state that `finally` still runs after the catch block, even if that block throws. Control may not jump **out** of a `finally` block. `try { return 1; } finally { return 2; }` does not compile: the SDK reports **CS0157**, "Control cannot leave the body of a finally clause". C# therefore never lets a `finally` silently override a return value. ## Order across nested try statements When an exception leaves several nested `try` statements, the pieces run in a fixed order once a handler is found: 1. The `finally` blocks of the frames being left run **innermost first**. 2. The chosen catch block runs. 3. That statement's own `finally` block runs after the catch block. 4. Unless the catch block throws or returns, execution continues with the statement after the `try` statement that handled the exception. So a `finally` deep in a helper method always runs before the catch block of its caller, which is what lets the helper restore its own state before anyone handles the failure. ## When finally does not run The C# reference says the cases where `finally` blocks do not execute involve **immediate termination** of the program. Each of these was checked on .NET 10: | Situation | What happens | |---|---| | `Environment.FailFast("...")` | the runtime prints the message and stack, then terminates; the `finally` line never printed | | `Environment.Exit(3)` inside the `try` | the process exits with that code; the `finally` line never printed | | Stack overflow (deep or infinite recursion) | the runtime prints `Stack overflow.` and ends the process; a `StackOverflowException` cannot be caught, and `finally` does not run | | Process killed from outside (a container stop that escalates to a kill, a crash of the host) | nothing in the process runs any more | | `try` block that never ends (infinite loop, deadlock) | control never leaves, so `finally` is never reached | There is also a grey zone. For an exception that **nothing catches**, the docs say that whether `finally` runs depends on whether an unwind operation is triggered. Do not build correctness on it: an unhandled exception is going to end the process, and anything that must survive (a ledger write, a message acknowledgement) needs its own durable design. ## An exception inside finally replaces the original If a `finally` block throws while another exception is propagating, **the new exception replaces the old one**. The original is not attached as an inner exception, not aggregated, simply gone. In the code example the `try` block fails with `InvalidOperationException("item INV-7 declined")`, the `finally` block throws `IOException("audit file already closed")`, and the caller's `catch (Exception)` prints only the `IOException`. The log points at a cleanup problem and hides the real failure. The code-analysis rule **CA2219**, "Do not raise exceptions in exception clauses", targets exactly this: an exception raised in a `finally` block hides the active exception. The .NET best-practices page repeats it: do not raise exceptions in `finally` clauses. ## Writing finally blocks that cannot hide failures 1. **Keep cleanup small and non-throwing.** Reset fields, release flags, call methods documented not to throw. 2. **Guard risky cleanup.** If cleanup can fail, wrap it in its own `try`/`catch` inside the `finally` block, and log the cleanup failure instead of letting it escape. 3. **Do not put business steps in `finally`.** Committing a payment or sending a receipt is not cleanup; if it belongs to the success path, put it at the end of the `try` block. 4. **Do not rely on finally for process-level guarantees.** Something that must happen even if the process dies needs a durable mechanism, not a `finally` block.

  • In `try { return Compute(); } finally { counter++; }`, which runs first, `Compute()` or `counter++`?
    `Compute()`. The return value is evaluated first, then control leaves the `try` block, which runs the `finally` block, and only then does the method return the already-computed value. The `finally` block cannot change it with its own `return`, because that is CS0157.
  • How would you make cleanup that may throw safe inside a `finally` block?
    Wrap the risky call in its own `try`/`catch` inside the `finally` block and log the cleanup failure there. The exception that was already propagating then reaches the caller unchanged, and the cleanup problem is still recorded.

  • finally always runs, no matter how the process ends
  • a return inside finally can override the try block's return value
  • an exception thrown in finally is attached to the original as its InnerException
  • a StackOverflowException can be caught so the finally block runs
  • finally is a good place to commit the transaction or send the receipt