C# · Lesson 7

Exceptions, guards and resources

Throwing and catching well in .NET (which exceptions to use, custom types, `when` filters, `throw;` vs `throw ex;`), guard clauses, when a result type beats an exception, deterministic cleanup with `IDisposable`, `IAsyncDisposable`, `using` and `finally`, and logging errors with context.

12 min read

In short

  • Throw the built-in exception that fits
  • Guard public methods: ThrowIfNull and friends
  • Catch only what you handle; filter with when
  • throw; keeps the stack, throw ex; loses it
  • Results for expected failures, exceptions for bugs
  • using disposes in reverse order, even on errors

Exceptions are .NET's main error channel. The framework throws them, ASP.NET Core catches the ones you don't and turns them into a 500 response, and your monitoring (OpenTelemetry, or an APM tool) records each one with its stack trace. Handle them well and a production problem takes minutes to diagnose: the log says which order, which step, and the stack trace points at the line. Handle them badly (swallowed exceptions, lost stack traces, a NullReferenceException three layers away from the real mistake) and the same problem takes days.

The second half of the topic is about resources: database connections, streams, message queue senders, locks. The garbage collector cleans up eventually, but never on your schedule. Forget to release a connection and the pool runs dry under load.

All C# blocks below have a ▶ Try button.

The exceptions you'll throw

You rarely need a new exception type. The base library has one for most situations, and callers already know how to handle them:

ThrowWhen
ArgumentNullExceptiona required argument is null
ArgumentExceptionan argument is invalid: empty, wrong format, inconsistent with another argument
ArgumentOutOfRangeExceptiona number, index or enum value is outside the allowed range
InvalidOperationExceptionthe object's current state doesn't allow this call ("the order has already shipped")
ObjectDisposedExceptionthe object was used after Dispose
NotSupportedExceptionthis implementation never supports the operation (a read-only collection's Add)
KeyNotFoundException / FormatExceptiona lookup by key failed / text isn't in the expected format
TimeoutException, OperationCanceledExceptionan operation took too long / was cancelled

Never throw Exception itself, NullReferenceException or IndexOutOfRangeException. The last two mean "there's a bug here" and should only ever come from the runtime. NotImplementedException is for placeholders, like the starters in this lab, never for shipped code.

The types form a hierarchy, and catch matches subclasses: catch (ArgumentException) also catches ArgumentNullException and ArgumentOutOfRangeException, and catch (OperationCanceledException) also catches TaskCanceledException.

try, catch, finally

▶ Try
Console.WriteLine(Parse("42"));
Console.WriteLine(Parse("forty-two"));

static string Parse(string text)
{
    try
    {
        return $"parsed {int.Parse(text)}";
    }
    catch (FormatException e)
    {
        return $"bad input: {e.Message}";
    }
    finally
    {
        Console.WriteLine($"finally runs for '{text}'"); // even after a return
    }
}
  • catch clauses are checked top to bottom, and the first one whose type matches wins. A clause that can never run because an earlier one catches a base type is a compile error (CS0160), so specific types go first.
  • finally always runs: after normal completion, after return, and when an exception passes through, caught or not. It's where cleanup goes. Keep it simple, because an exception thrown inside finally replaces the one already in flight, and the original is lost.
  • Catch only what you can handle. A catch (Exception) belongs at a boundary: the top of a request (ASP.NET Core has one for you), a message handler, a background job. There you log it and decide what the caller sees. Everywhere else, let exceptions fly.

Rethrowing: throw; vs throw ex;

▶ Try
try { LoadOrder(); }
catch (Exception e) { Console.WriteLine(e.StackTrace!.Contains("ReadFromDisk") ? "throw; kept the original stack" : "stack lost"); }

try { LoadOrderBadly(); }
catch (Exception e) { Console.WriteLine(e.StackTrace!.Contains("ReadFromDisk") ? "stack kept" : "throw ex; lost where it really happened"); }

static void ReadFromDisk() => throw new IOException("disk on fire");

static void LoadOrder()
{
    try { ReadFromDisk(); }
    catch (IOException) { throw; }       // rethrows the same exception, stack trace intact
}

static void LoadOrderBadly()
{
    try { ReadFromDisk(); }
    catch (IOException ex) { throw ex; } // restarts the stack trace here (analyzer warning CA2200)
}
  • throw; rethrows the exception you caught, with its original stack trace.
  • throw ex; throws it again as if it started here. The frames that show where it really happened are gone. Run the block above and you'll also see the build warning CA2200 for it.
  • To add context, wrap it and keep the original as InnerException: throw new OrderImportException($"Could not import order {orderId}", ex);. Logs show both stack traces.
  • ExceptionDispatchInfo.Throw(ex) rethrows an exception you stored earlier (say, from another task) and keeps its stack. await does exactly this for you.

Exception filters: when

▶ Try
using System.Net;

foreach (var status in new[] { HttpStatusCode.NotFound, HttpStatusCode.ServiceUnavailable, HttpStatusCode.BadRequest })
{
    try
    {
        throw new HttpRequestException($"HTTP {(int)status}", null, status);
    }
    catch (HttpRequestException e) when (e.StatusCode == HttpStatusCode.NotFound)
    {
        Console.WriteLine("404: treat as 'no profile yet'");
    }
    catch (HttpRequestException e) when (e.StatusCode is HttpStatusCode.ServiceUnavailable or HttpStatusCode.TooManyRequests)
    {
        Console.WriteLine($"{(int)e.StatusCode!}: transient, retry later");
    }
    catch (HttpRequestException e)
    {
        Console.WriteLine($"other failure: {e.Message}");
    }
}
  • The filter runs before the stack unwinds. If it returns false, that catch is skipped as if it weren't there, and the exception keeps looking for a handler with nothing changed. That's better than catching, checking with if, and rethrowing.
  • Typical filters: a status code (HttpRequestException.StatusCode, or a cloud SDK's service exception: AWS's AmazonServiceException.StatusCode, Azure's RequestFailedException.Status, Google Cloud's GoogleApiException.HttpStatusCode), "was it our cancellation?" (when (cancellationToken.IsCancellationRequested)), or an error code on a database exception.
  • Because filters run first, a filter that logs and returns false records the exception with the full stack, without catching it: catch (Exception e) when (LogAndContinue(e)) { }.

Custom exceptions

Write your own when callers need to catch that failure specifically, or when it carries data they act on. With C# 12 primary constructors they're short:

▶ Try
try
{
    new Account(50m).Withdraw(80m);
}
catch (InsufficientFundsException e)
{
    Console.WriteLine($"{e.Message} Short by {e.Shortfall}.");
}

public sealed class InsufficientFundsException(decimal balance, decimal requested)
    : InvalidOperationException($"Cannot withdraw {requested} from a balance of {balance}.")
{
    public decimal Balance { get; } = balance;
    public decimal Requested { get; } = requested;
    public decimal Shortfall => Requested - Balance;
}

public sealed class Account(decimal balance)
{
    public decimal Balance { get; private set; } = balance;

    public void Withdraw(decimal amount)
    {
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
        if (amount > Balance) throw new InsufficientFundsException(Balance, amount);
        Balance -= amount;
    }
}
  • End the name with Exception, derive from the closest built-in type (here InvalidOperationException, so generic handlers still understand it), and make it sealed unless you're designing a hierarchy.
  • Put the data in properties, not only in the message. Code should never have to parse e.Message.
  • A shared base such as DomainException lets an API map every business rule violation to a 4xx in one place.
  • You'll see [Serializable] and a serialization constructor on older exception classes. Binary serialization is obsolete in modern .NET, so you can leave both out.

Guard clauses

Public methods check their arguments first and fail fast. .NET 6, 7 and 8 added a one-line helper for each common check, and the helpers fill in ParamName from the argument expression automatically:

▶ Try
var service = new TransferService();
Try(() => service.Transfer(null!, "NL02BANK0002", 10m));
Try(() => service.Transfer("NL01BANK0001", "   ", 10m));
Try(() => service.Transfer("NL01BANK0001", "NL02BANK0002", -5m));
Try(() => service.Transfer("NL01BANK0001", "NL02BANK0002", 25m));

static void Try(Action action)
{
    try { action(); }
    catch (ArgumentException e) { Console.WriteLine($"{e.GetType().Name} for '{e.ParamName}'"); }
}

class TransferService
{
    public void Transfer(string fromIban, string toIban, decimal amount)
    {
        ArgumentNullException.ThrowIfNull(fromIban);
        ArgumentException.ThrowIfNullOrWhiteSpace(toIban);
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
        Console.WriteLine($"transfer {amount} from {fromIban} to {toIban}");
    }
}
HelperSince
ArgumentNullException.ThrowIfNull(x).NET 6
ArgumentException.ThrowIfNullOrEmpty(s).NET 7
ArgumentException.ThrowIfNullOrWhiteSpace(s).NET 8
ArgumentOutOfRangeException.ThrowIfNegative, ThrowIfNegativeOrZero, ThrowIfZero, ThrowIfGreaterThan, ThrowIfLessThan, ....NET 8
ObjectDisposedException.ThrowIf(disposed, this).NET 7

ThrowIfNullOrWhiteSpace throws ArgumentNullException for null and ArgumentException for blank text, so callers catching ArgumentException get both.

Guards are for programmer mistakes, not for user input. A guard that fires means a bug in the calling code, and ending up as a 500 is right. A user who typed an invalid IBAN should get a 400 with a helpful message, which is a validation result, not an exception.

Exceptions or result types?

Use an exception when...Use a result type when...
it's a bug or a broken invariantthe failure is an expected business outcome
the caller can't do anything useful about it herethe caller must decide what happens next
it's rare: database down, config missing, a timeoutit's common: validation failed, not found, insufficient funds

Throwing is also slow compared with returning: the runtime captures a stack trace and unwinds frames, which costs microseconds each time. That's nothing for a rare failure, but too much as control flow in a loop over 100,000 imported rows.

A result type makes the possible failures part of the signature, like F#'s Result<'T, 'E> and TypeScript's { ok: true, value } | { ok: false, error }. C# has none built in. Teams write a small one or use a library such as ErrorOr, OneOf or FluentResults:

▶ Try
using System.Globalization;

foreach (var text in new[] { "12.50", "abc", "-3" })
{
    var result = ParseAmount(text);
    Console.WriteLine(result.IsSuccess ? $"ok {result.Value}" : $"error: {result.Error}");
}

static Result<decimal> ParseAmount(string text) =>
    !decimal.TryParse(text, NumberStyles.Number, CultureInfo.InvariantCulture, out var amount) ? Result<decimal>.Fail("not a number")
    : amount <= 0 ? Result<decimal>.Fail("must be positive")
    : Result<decimal>.Ok(amount);

public readonly record struct Result<T>(bool IsSuccess, T? Value, string? Error)
{
    public static Result<T> Ok(T value) => new(true, value, null);
    public static Result<T> Fail(string error) => new(false, default, error);
}

At the edge of the API, results become HTTP responses, which is where the switch expressions from the pattern matching topic come in: result.IsSuccess ? Results.Ok(result.Value) : Results.Problem(...). Exercise 4 builds a fuller version with Map, Bind and Match.

Deterministic cleanup: IDisposable and using

IDisposable.Dispose() releases a resource now. using guarantees the call, even when an exception escapes, because it compiles to try/finally:

▶ Try
using (var connection = new Tracked("connection"))
{
    using var transaction = new Tracked("transaction"); // a using declaration: disposed at the end of the scope
    Console.WriteLine("work");
}
Console.WriteLine("after the block");

try
{
    using var file = new Tracked("file");
    throw new InvalidOperationException("boom");
}
catch (InvalidOperationException) { Console.WriteLine("caught, and the file was already closed"); }

sealed class Tracked : IDisposable
{
    private readonly string _name;
    public Tracked(string name) { _name = name; Console.WriteLine($"open {_name}"); }
    public void Dispose() => Console.WriteLine($"close {_name}");
}

Disposal happens in reverse order of acquisition: the transaction closes before the connection it runs on.

When you write Dispose yourself:

  • Make it idempotent: calling it twice must be harmless.
  • After Dispose, other members throw ObjectDisposedException (ObjectDisposedException.ThrowIf(_disposed, this)).
  • Dispose what you own, not what you were given. If your class created the stream, it disposes it. If the stream was passed in, or injected by the DI container, the creator is responsible for it.
  • Avoid throwing from Dispose. It often runs during an exception, and a second one hides the first.
  • The full "dispose pattern" with Dispose(bool disposing) and a finalizer is only for classes that directly hold unmanaged handles. That's rare (and SafeHandle covers it). A sealed class that wraps other disposables just needs a plain Dispose.

IAsyncDisposable and await using

Some cleanup does I/O: flushing a buffer to object storage, closing a broker connection, sending a final message. Doing that in Dispose would block a thread, so those types implement IAsyncDisposable and you write await using. Message broker clients that keep a connection open work this way (Azure Service Bus's ServiceBusSender, Google Cloud Pub/Sub's PublisherClient, RabbitMQ's IChannel), as do streams and EF Core's DbContext.

▶ Try
await using (var writer = new BufferedUploader())
{
    await writer.WriteAsync("line 1");
    await writer.WriteAsync("line 2");
} // DisposeAsync flushes here
Console.WriteLine("done");

sealed class BufferedUploader : IAsyncDisposable
{
    private readonly List<string> _buffer = new();

    public Task WriteAsync(string line)
    {
        _buffer.Add(line);
        return Task.CompletedTask;
    }

    public async ValueTask DisposeAsync()
    {
        await Task.Delay(10); // pretend to upload over the network
        Console.WriteLine($"flushed {_buffer.Count} lines");
    }
}

TypeScript now has the same feature (using and await using with Symbol.dispose and Symbol.asyncDispose; see the Advanced async TypeScript topic). F# has use for IDisposable, but even inside task { } it doesn't accept an IAsyncDisposable, so F# code calls DisposeAsync() in a finally.

Logging errors with context

// ILogger in a .NET service (not runnable here)
public async Task ImportAsync(string orderId, CancellationToken ct)
{
    using var scope = _logger.BeginScope(new Dictionary<string, object> { ["OrderId"] = orderId });
    try
    {
        await _importer.RunAsync(orderId, ct);
    }
    catch (ImportException ex) when (ex.IsRetryable)
    {
        _logger.LogWarning(ex, "Import of order {OrderId} failed at step {Step}, will retry", orderId, ex.Step);
        throw;
    }
}
  • Pass the exception object first: LogError(ex, "..."). Then the stack trace and inner exceptions are recorded. Putting ex.Message in the text throws all of that away.
  • Use message templates, not string interpolation. With {OrderId}, the value becomes a searchable property (an OrderId field you can filter on in CloudWatch Logs, Azure Monitor, Google Cloud Logging or Seq) and every occurrence shares one template. With $"...", every message is unique, nothing is searchable, and the string is built even when that log level is off.
  • Log once, where you handle it. "Log and rethrow" at every layer produces the same error five times. Either handle it (and log), or add context by wrapping it, and let the boundary log.
  • Scopes (BeginScope) attach properties such as an order id, a message id or a correlation id to every log line inside, including the framework's own.
  • Never log secrets or personal data: connection strings, tokens, full card numbers.
  • In ASP.NET Core, unhandled exceptions go to app.UseExceptionHandler(), and builder.Services.AddProblemDetails() turns them into a 500 with a ProblemDetails body and a trace id. Since .NET 8, IExceptionHandler lets you map your own exception types to status codes. Outside Development, the stack trace never goes into the response.

Common mistakes

  • catch (Exception) { }: the error vanishes, and the system carries on in an unknown state.
  • throw ex; instead of throw;.
  • Catching inside a loop and continuing silently, so one bad record hides a systematic failure.
  • Exceptions as control flow on a hot path (validating every row of a big import by catching FormatException).
  • A finally or Dispose that throws and hides the real exception.
  • Not disposing HttpResponseMessage, Streams or CancellationTokenSources you created, or disposing an HttpClient or DbContext that the DI container gave you.
  • Returning null to mean "it failed", so the caller gets a NullReferenceException far away from the cause. Use a Try method or a result type instead.

The exercises

  1. Guard clauses: ArgumentNullException.ThrowIfNull and friends, with the right exception types.
  2. Connection lease: an IDisposable that returns a connection to a pool, exactly once.
  3. Classifying HTTP failures: exception filters, throw;, and cancellations that aren't yours.
  4. A Result type: Map, Bind and Match for withdrawals that fail for expected reasons.
  5. Resource stack: an IAsyncDisposable that cleans up in reverse order and reports every failure.
  6. Error boundary: turn exceptions into ProblemDetails responses with structured logs.

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 10-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.

Open in the app