Custom Exceptions: Naming the Failure

Custom Exceptions: Naming the Failure in C#: Two cars break down on the same road. The first has a dashboard that lights up a single amber engine outline —…

The Analogy: The Diagnostic Trouble Code

Two cars break down on the same road. The first has a dashboard that lights up a single amber engine outline — something, somewhere, is unhappy. The second reports P0301, and the mechanic reads it as "cylinder 1 misfire" before the bonnet is even open. Same fault, same car, wildly different repair bill, because the second car named its failure.

Built-in exception types are the amber light. InvalidOperationException("cannot withdraw") tells the caller that something in the operation was invalid, and the only way to find out which something is to read the message with a human eye. That is fine when the answer is "log it and give up". It is useless when the caller wants to react — top up the account, retry a different way, ask the user for one specific field.

A custom exception is the trouble code. It has a type a catch clause can name, and it carries structured data — the exact shortfall, the row number, the field that failed — as properties, not as prose buried in a sentence. Writing one is three lines of ceremony; the payoff is that the code handling the failure can make a decision instead of a guess.


Syntax or Core Structure

A custom exception is any class that derives from System.Exception. Convention asks for three things: a name ending in Exception, constructors that hand a message down to base, and read-only properties for the data a handler will want.

using System;

class InsufficientFundsException : Exception
{
    public decimal Shortfall { get; }

    public InsufficientFundsException(decimal shortfall)
        : base("short by " + shortfall)
    {
        Shortfall = shortfall;
    }
}

class AccountFrozenException : Exception
{
    public AccountFrozenException(string reason) : base(reason) { }

    // Always offer an inner-exception overload: it is how a cause survives.
    public AccountFrozenException(string reason, Exception inner) : base(reason, inner) { }
}

class Account
{
    public decimal Balance { get; private set; } = 40m;
    public bool Frozen { get; set; }

    public void Withdraw(decimal amount)
    {
        if (Frozen)
            throw new AccountFrozenException("account is frozen");

        if (amount > Balance)
            throw new InsufficientFundsException(amount - Balance);

        Balance -= amount;
    }
}

class Program
{
    static void Main()
    {
        var account = new Account();

        Attempt(account, 25m);
        Attempt(account, 50m);

        account.Frozen = true;
        Attempt(account, 5m);
    }

    static void Attempt(Account account, decimal amount)
    {
        try
        {
            account.Withdraw(amount);
            Console.WriteLine("took " + amount + ", balance " + account.Balance);
        }
        catch (InsufficientFundsException ex)
        {
            // The property lets the caller REACT, not merely report.
            Console.WriteLine("declined: " + ex.Message + " (top up " + ex.Shortfall + ")");
        }
        catch (AccountFrozenException ex)
        {
            Console.WriteLine("blocked: " + ex.Message);
        }
    }
}

Output:

took 25, balance 15
declined: short by 35 (top up 35)
blocked: account is frozen

The two catch clauses are the whole argument for custom types. With a single InvalidOperationException for both failures, that method would have to inspect the message text to tell "no money" from "frozen" — and the first time somebody rewords the message, the handling breaks silently.


Technical Depth: When a New Type Earns Its Keep

The honest test is one question: will a caller write a catch for it, or read a property off it? If the answer is no, a built-in type with a good message is better, because every new public exception type is a permanent part of your API.

SituationThrow this
Argument was nullArgumentNullException
Argument out of rangeArgumentOutOfRangeException
Object is in the wrong stateInvalidOperationException
Feature genuinely not written yetNotImplementedException
Operation will never be supported hereNotSupportedException
Caller must react differently to this specific failureA custom type
The failure carries data (row, field, shortfall, retry-after)A custom type
A whole library needs one catchable umbrellaA custom base type

The constructor set

The framework guideline is three public constructors, and the reason for each is practical rather than ceremonial:

ConstructorWhy it exists
MyException()Tools and serializers that create instances generically
MyException(string message)The ordinary throw site
MyException(string message, Exception inner)Wrapping a lower-level cause without losing it

If you add required data, keep those three shapes in spirit: take the data plus an optional Exception? inner = null, and pass both to base. Dropping the inner-exception overload is the single most common design mistake in custom exceptions, because it forces the next developer to choose between context and cause.

Inheriting from the right base

Derive from Exception. Not ApplicationException — Microsoft's own guidance retired it, because the promised split between "framework errors" and "application errors" never happened and nobody catches it. Not SystemException either, which is reserved for the runtime. And never derive from a type whose meaning you are not honouring: an ArgumentException subclass that is not about an argument will confuse every handler that catches it.

For a library, a small hierarchy pays for itself:

public abstract class ImportException : Exception { /* ... */ }
public sealed class MalformedRowException : ImportException { /* ... */ }
public sealed class BadFieldException  : ImportException { /* ... */ }

Consumers who care about detail catch the leaves; consumers who just want to skip a file catch ImportException and know they have covered everything you throw deliberately. Mark the leaves sealed unless you have a reason to allow further derivation, and make them public — an internal exception type cannot be named in a catch clause outside your assembly, which makes it unhandleable in practice.

Data on the exception

Properties are the right place for structured detail, and they should be immutable — an exception is a report, not a workspace. Exception also has an IDictionary called Data for loose key/value context that no catch clause will branch on:

catch (BadFieldException ex)
{
    ex.Data["file"] = path;     // extra breadcrumbs for the log
    throw;                      // keeps the original stack trace
}

Use Data for logging breadcrumbs and typed properties for anything a handler must read. What you should not do is compose a message such as "row 4 field age" and expect the handler to parse it back out; that turns your prose into an accidental data format.

The serialization constructor you no longer need

Older tutorials add [Serializable] and a protected MyException(SerializationInfo, StreamingContext) constructor. That existed for BinaryFormatter-based remoting, which is obsolete from .NET 5 and removed in .NET 9 for being unsafe by design. Unless you are maintaining code that crosses an AppDomain boundary the old way, leave both out; modern boundaries carry a serialized problem detail payload, not a live exception object.


Real World Example: A CSV Import With a Diagnosis

An import that fails is not interesting. An import that tells you which row, which field, what the underlying cause was, and what to do about it is the difference between a support ticket and a five-second fix. Here the library defines one abstract base with a Row and an Advice, and two concrete failures underneath it.

using System;
using System.Collections.Generic;

abstract class ImportException : Exception
{
    protected ImportException(int row, string message, Exception? inner = null)
        : base(message, inner) => Row = row;

    public int Row { get; }
    public abstract string Advice { get; }
}

sealed class MalformedRowException : ImportException
{
    public MalformedRowException(int row, int fieldCount)
        : base(row, "expected 3 fields, found " + fieldCount) => FieldCount = fieldCount;

    public int FieldCount { get; }
    public override string Advice => "check for a stray or missing comma";
}

sealed class BadFieldException : ImportException
{
    public BadFieldException(int row, string field, Exception inner)
        : base(row, "field '" + field + "' is unreadable", inner) => Field = field;

    public string Field { get; }
    public override string Advice => "correct the value or blank the cell";
}

record Employee(string Name, int Age, decimal Salary);

class Program
{
    static void Main()
    {
        string[] rows =
        {
            "Ada,36,5200",
            "Grace,45",
            "Alan,young,4800",
            "Katherine,41,6100"
        };

        var staff = new List<Employee>();

        for (int i = 0; i < rows.Length; i++)
        {
            try
            {
                staff.Add(ParseRow(i + 1, rows[i]));
                Console.WriteLine("row " + (i + 1) + " ok");
            }
            catch (ImportException ex)   // one catch covers the whole family
            {
                Console.WriteLine("row " + ex.Row + " failed: " + ex.Message);
                Console.WriteLine("        advice: " + ex.Advice);

                if (ex.InnerException is not null)
                    Console.WriteLine("        cause:  " + ex.InnerException.GetType().Name);
            }
        }

        Console.WriteLine(staff.Count + " of " + rows.Length + " rows imported");
    }

    static Employee ParseRow(int row, string text)
    {
        string[] parts = text.Split(',');

        if (parts.Length != 3)
            throw new MalformedRowException(row, parts.Length);

        int age;
        try { age = int.Parse(parts[1]); }
        catch (FormatException inner) { throw new BadFieldException(row, "age", inner); }

        decimal salary;
        try { salary = decimal.Parse(parts[2]); }
        catch (FormatException inner) { throw new BadFieldException(row, "salary", inner); }

        return new Employee(parts[0], age, salary);
    }
}

Output:

row 1 ok
row 2 failed: expected 3 fields, found 2
        advice: check for a stray or missing comma
row 3 failed: field 'age' is unreadable
        advice: correct the value or blank the cell
        cause:  FormatException
row 4 ok
2 of 4 rows imported

The FormatException was never thrown away — it is hanging off InnerException, so a log can print the full chain while the user-facing line stays readable. And because Advice is an abstract member of the base, adding a third failure type to this library forces whoever writes it to answer "what should a human do about this?" at the same moment they invent the failure.


Common Mistakes

  1. Deriving from ApplicationException. It was meant to separate application errors from framework errors, that separation never worked, and the current guidance is to derive from Exception directly. Nobody catches ApplicationException, so it buys you nothing.
  2. Omitting the (message, Exception inner) constructor. Without it, anyone wrapping a lower-level failure in your exception must discard the cause. Add the overload even if your own code does not use it yet.
  3. Making the exception type internal. A caller in another assembly cannot write catch (MyException) for a type it cannot see, so the failure becomes uncatchable-by-name. Exception types that cross an assembly boundary must be public.
  4. One AppException with an error-code enum. catch (AppException ex) when (ex.Code == ErrorCode.NoFunds) reimplements, badly, what the type system already does. Use distinct types and let catch do the matching.
  5. Putting the data only in the message. "row 4: field age" forces handlers to parse English. Expose Row and Field as properties and let the message be a human sentence built from them.
  6. Mutable properties. A settable Row invites a handler to "correct" the report as it travels. Make exception state read-only; it is a record of what happened.
  7. Doing real work in the constructor. Reading a file, formatting a huge object graph or writing to a log inside an exception constructor runs at the worst possible moment and can throw a second exception on top of the first. Build the exception, then let a handler decide what to record.
  8. Naming without the suffix, or naming the location. BadThing and ImportServiceError both fail the test. Name the condition and end with Exception: MalformedRowException, InsufficientFundsException.

Best Practices

  • Create a custom type only when a handler will catch it by name or read data off it; otherwise use a built-in type with a precise message.
  • Derive from Exception, keep the class public, and seal the concrete leaves.
  • Give every custom exception the three conventional constructors, always including one that accepts an inner exception.
  • Give a library one abstract base exception so consumers can catch the family in a single clause.
  • Expose structured detail as immutable properties; keep Exception.Data for logging breadcrumbs only.
  • Write messages for the person reading the log: state what failed and what was expected, without a stack trace's worth of detail.
  • Consider an abstract member such as Advice on your base type to force each new failure to explain its own remedy.
  • Skip [Serializable] and the SerializationInfo constructor in new code; carry failures across process boundaries as data, not as live exception objects.

Practice Exercises

  1. Name a failure. Write OutOfStockException with an immutable Requested and Available (both int) and a message built from them. Throw it from an Order(int quantity) method and catch it in Main, printing how many units the customer would have to remove to succeed.
  2. Preserve the cause. Write ConfigurationException(string key, Exception inner) and throw it from a method that calls int.Parse on a bad setting value. In the handler, print ex.Message, then ex.InnerException!.GetType().Name, then walk the whole chain in a while loop until InnerException is null.
  3. Build a family. Create an abstract ShippingException with two sealed subclasses (AddressUnknownException, ParcelTooHeavyException), each with one property of its own. Write one catch (ShippingException) that prints a common line, and prove both subclasses land in it.
  4. Refactor the code enum. Take a single exception class that carries ErrorCode Code { get; } and three when filters, and split it into three types plus a shared base. Compare the two catch sections and write down which one a new team member would understand faster, and why.