IC Improve Code Recipes

Recipe 5.2 · C#

throw; Versus throw ex;

Problem

Code catches an exception, does some cleanup or logging, and rethrows it with throw ex;. The stack trace now starts at the rethrow, not at the line that failed. You see that SaveOrder threw, but not that the real failure was three calls deeper, in a currency conversion.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not this: the original stack trace is lost at "throw ex".
public void SaveOrder(Order order)
{
    SqlTransaction tx = conn.BeginTransaction();
    try
    {
        InsertHeader(order, tx);
        InsertLines(order, tx);
        tx.Commit();
    }
    catch (Exception ex)
    {
        tx.Rollback();
        throw ex;
    }
}

The improved recipe

Use throw; to rethrow the same exception. When you want to add context, throw a new exception and pass the original as the inner exception.

C#
using System;
using System.Data.Common;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace ImproveCode.Errors;

public static class TransactionRunner
{
    public static async Task RunAsync(
        DbConnection connection,
        Func<DbTransaction, CancellationToken, Task> work,
        CancellationToken ct = default)
    {
        await using DbTransaction tx =
            await connection.BeginTransactionAsync(ct);

        try
        {
            await work(tx, ct);
            await tx.CommitAsync(ct);
        }
        catch
        {
            // Roll back even if the caller has cancelled.
            await tx.RollbackAsync(CancellationToken.None);
            throw; // same exception, original stack trace
        }
    }
}

public sealed class InvoiceExporter
{
    public void Export(int invoiceId, string folder)
    {
        string path = Path.Combine(folder, $"invoice-{invoiceId}.pdf");

        try
        {
            File.WriteAllBytes(path, Render(invoiceId));
        }
        catch (IOException ex)
        {
            // New exception adds context; the original is kept inside.
            throw new InvalidOperationException(
                $"Could not export invoice {invoiceId} to {path}.", ex);
        }
    }

    private static byte[] Render(int invoiceId) =>
        BitConverter.GetBytes(invoiceId); // real rendering here
}

How it works

An exception's stack trace is captured when it is thrown. throw ex; is a new throw of the same object, so the runtime resets the trace to the current method. throw; (only legal inside a catch) rethrows the exception in flight and leaves the trace intact, so the log shows the original failing line.

TransactionRunner uses a bare catch followed by throw;. That is one of the few places a catch-everything block is correct: it doesn't handle the exception, it only guarantees cleanup. Rolling back with CancellationToken.None makes sure a cancelled request still releases its locks. If the work succeeded, the rollback never runs. If the commit itself fails, the rollback runs and the commit's exception continues upward.

InvoiceExporter translates instead. The IOException alone says "the process cannot access the file," which doesn't tell the reader which invoice or why it mattered. The new exception says that, and InnerException keeps the full original, stack trace included. Logging frameworks print the whole chain. That is what the ex parameter in LogError(ex, ...) is for.

Variations and pitfalls

  • throw ex; triggers analyzer warning CA2200. Make it an error in your .editorconfig: dotnet_diagnostic.CA2200.severity = error.
  • Wrapping without passing the inner exception (throw new Exception("Save failed")) is worse than throw ex;. It loses both the stack and the original type and message.
  • Don't wrap at every layer. One translation at a meaningful boundary (repository to service, service to API) is enough. Five layers of "an error occurred" wrappers just make the log longer.
  • Sometimes you need to rethrow later, outside the catch, for example after trying a fallback. ExceptionDispatchInfo.Capture(ex) stores the exception, and .Throw() rethrows it later with the original stack trace preserved.
  • An exception filter (catch (X ex) when (Log(ex)) with Log returning false) lets you log without catching at all, so the stack is never unwound. It's a neat trick, but use it sparingly; most readers don't expect it.