Skip to content
Tutorials Center
My learning

Topics

Lesson 87 of 182 ยท Null Safety and Errors

Exception Filters and Error Handling Patterns

Learn C# exception filters with when, the TryParse pattern, Result types, ExceptionDispatchInfo, retry with backoff, and global handlers for unhandled exceptions, with runnable examples.

A catch block normally says which type of exception it handles. Often that is not enough: an HttpRequestException with status 404 is something you can handle, one with status 500 is not; an IOException caused by a full disk is different from one caused by a missing file. Before C# 6 you caught the whole type, inspected it, and rethrew what you did not want, which disturbed the stack and the debugging experience. An exception filter lets the catch itself decide, with a when clause.

This lesson starts with filters and a surprising property of them, then moves to the broader question of error handling design: the TryParse pattern, a Result type that makes failure visible in the signature, ExceptionDispatchInfo for rethrowing across boundaries, retries with backoff, and last-resort global handlers.

The when clause

catch (SomeException e) when (condition) catches only if the condition is true. If it is false the runtime acts as if that catch were not there and keeps looking at the next clause and then at callers.

C# Handle only the cases you understand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The same exception type is handled three different ways depending on its data. Without filters, you would write one catch (ApiException e) with an if/else chain inside, rethrowing the unhandled branch.

Why not catch and rethrow?

Filters are not only tidier; they are better. A filter runs before the stack is unwound, during the first pass of the runtime's exception handling. If the filter says no, nothing has been unwound yet: no finally block in between has run, and a debugger that breaks on unhandled exceptions stops at the original throw site with all the locals available. After catch ... throw; the program has already unwound to the catch.

The ordering is observable:

C# Filters run before finally blocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The output starts with the filter, then "finally in Level1", then the catch block. This two-pass behavior is the reason a method called from a filter can observe the program as it was at the time of the throw.

The logging trick

Because a filter that returns false lets the exception continue untouched, you can use a filter to observe without handling:

C# Log from a filter and let the exception go on

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

It is a known idiom, but use it sparingly: a filter must be fast and must not throw. If it throws, the exception is swallowed and the filter counts as false.

Filters can use any boolean expression: properties of the exception, the inner exception (e.InnerException is TimeoutException), local variables, even a flag such as when (!_shuttingDown).

Pattern 1: the TryParse shape

For failures that are routine, avoid exceptions altogether with a method that returns bool and gives the result through an out parameter. The .NET libraries do it with int.TryParse, Dictionary.TryGetValue, Uri.TryCreate, Enum.TryParse and many more. It is fast and makes the failure impossible to forget.

C# Writing your own Try method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The convention: always assign all out parameters (to defaults on failure), never throw for bad data, and still throw for bad use (an argument that can never be valid). A good API often offers both: Parse that throws and TryParse that does not. The nullable attributes from Nullable Reference Types ([NotNullWhen(true)]) tell the compiler about the relation.

Pattern 2: a Result type

TryParse does not scale to methods that return a value and need to explain why they failed. A result type puts success or failure in the return type. C# has no built-in one, but a small one is easy:

C# A small Result type with records

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The caller is forced by the type to look at both cases (pattern matching on the hierarchy), and a missing branch can be caught at compile time when the hierarchy is closed. This style suits validation, parsing and business rules, where failure is data. Keep exceptions for the truly unexpected: out of memory, a broken database connection, a bug.

Exceptions Try pattern Result type
Failure is visible in the signature no yes yes
Good for rare, unrecoverable problems cheap yes/no with one value failures with reasons
Cost on failure high very low low
Propagates automatically up the stack yes no, you pass it along no, you pass it along

Pattern 3: ExceptionDispatchInfo

Sometimes you must catch an exception in one place and rethrow it in another: on a different thread, after cleanup code, or from a stored task result. Plain throw e; resets the stack trace. ExceptionDispatchInfo.Capture(e) snapshots the exception with its original trace, and .Throw() rethrows it, appending to the trace instead of replacing it. This is what await uses internally.

C# Rethrowing later without losing the original trace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The trace still names Worker.Explode, followed by the rethrow location at Main. Use it when you must hand an exception to another context; in ordinary code, throw; is enough.

Pattern 4: retry with backoff

Transient failures (a network blip, a busy server) often disappear if you wait and try again. A robust retry loop has four ingredients: a limit on attempts, a delay that grows (exponential backoff, so a struggling server is not hammered), a filter so only transient errors are retried, and a way to give up and surface the last error.

C# Retry only transient errors, with growing delays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The filter does double duty: it restricts retrying to TimeoutException and stops retrying on the last attempt, so the final failure escapes naturally with its original stack trace. Production code adds jitter (a random part of the delay so many clients do not retry in lockstep), a cancellation token and an overall time budget, and often uses a library such as Polly (a NuGet package, not available in our editor):

C#
// Read-only: needs the Polly NuGet package, which this editor does not have.
var pipeline = new ResiliencePipelineBuilder()
    .AddRetry(new RetryStrategyOptions
    {
        MaxRetryAttempts = 4,
        BackoffType = DelayBackoffType.Exponential,
        UseJitter = true,
    })
    .Build();

Only retry operations that are safe to repeat (idempotent): retrying "charge the card" without a deduplication key can charge twice.

Global handlers: the last line of defense

Some exceptions escape every catch. A last-resort handler cannot fix them, but it can log and shut down cleanly. In .NET:

  • AppDomain.CurrentDomain.UnhandledException is raised for an exception that is about to crash the process. You cannot cancel the crash here; you can write a log entry.
  • TaskScheduler.UnobservedTaskException reports exceptions of faulted tasks that nobody awaited (it no longer ends the process by default).
  • In ASP.NET Core, exception-handling middleware (app.UseExceptionHandler) turns exceptions into error responses; in desktop UI frameworks there are dispatcher-level events.
C# Logging a crash before the process ends (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The handler prints the "last chance" line to standard output, and then the runtime still prints the usual Unhandled exception. report and ends the process. Treat such a handler as a flight recorder, not a recovery tool: after an unhandled exception the program's state may be broken, and the sane response is to log, flush, and exit (letting a supervisor restart the process).

Choosing a strategy

  1. Prevent: validate inputs, use nullable annotations and guard clauses.
  2. Expected failures (bad user input, missing key, not found): TryXxx or a Result; no exceptions.
  3. Unexpected failures: throw; catch only where you can recover or add context; use filters to be selective.
  4. Transient failures: retry with backoff and a limit.
  5. Everything else: let it propagate to the top-level handler, which logs and reports.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does an exception filter (catch ... when (condition)) do when the condition is false?

    A false filter means the clause does not match. The search continues outward, and because filters run in the first pass, nothing has been unwound yet.
  2. 2. In which order do the filter, an inner finally block and the matching catch block run?

    The runtime first runs filters to find a handler, then unwinds (running inner finally blocks), then enters the chosen catch block.
  3. 3. Which is the best fit for validating a user-typed email address where failures are routine and need a reason?

    Routine, expected failures belong in the return type. A Result carries the reason, while a Try method is enough when you only need yes/no.
  4. 4. What is the advantage of ExceptionDispatchInfo.Capture(e).Throw() over throw e; in a later place?

    throw e; restarts the trace; ExceptionDispatchInfo preserves the original frames. It is the mechanism await uses.
  5. 5. Why use exponential backoff in a retry loop?

    Growing delays reduce load on a service that may already be overloaded; you still need a cap on attempts and, ideally, jitter.

Summary

  • catch (T e) when (condition) selects exceptions by data; a false filter leaves the exception untouched and the stack not unwound.
  • Filters run in the first pass, before finally blocks; they must be fast and must not throw.
  • Use the TryXxx pattern for cheap, routine failures and a Result type when you must explain why something failed.
  • ExceptionDispatchInfo preserves the original stack trace when an exception is rethrown elsewhere.
  • Retry only transient, idempotent operations, with a limit, exponential backoff (plus jitter) and a filter.
  • Global handlers log and shut down; they do not repair state.

Next: IDisposable, using and Finalizers