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.
| Situation | Throw this |
|---|---|
Argument was null | ArgumentNullException |
| Argument out of range | ArgumentOutOfRangeException |
| Object is in the wrong state | InvalidOperationException |
| Feature genuinely not written yet | NotImplementedException |
| Operation will never be supported here | NotSupportedException |
| Caller must react differently to this specific failure | A custom type |
| The failure carries data (row, field, shortfall, retry-after) | A custom type |
| A whole library needs one catchable umbrella | A custom base type |
The constructor set
The framework guideline is three public constructors, and the reason for each is practical rather than ceremonial:
| Constructor | Why 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
- Deriving from
ApplicationException. It was meant to separate application errors from framework errors, that separation never worked, and the current guidance is to derive fromExceptiondirectly. Nobody catchesApplicationException, so it buys you nothing. - 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. - Making the exception type
internal. A caller in another assembly cannot writecatch (MyException)for a type it cannot see, so the failure becomes uncatchable-by-name. Exception types that cross an assembly boundary must bepublic. - One
AppExceptionwith an error-code enum.catch (AppException ex) when (ex.Code == ErrorCode.NoFunds)reimplements, badly, what the type system already does. Use distinct types and letcatchdo the matching. - Putting the data only in the message.
"row 4: field age"forces handlers to parse English. ExposeRowandFieldas properties and let the message be a human sentence built from them. - Mutable properties. A settable
Rowinvites a handler to "correct" the report as it travels. Make exception state read-only; it is a record of what happened. - 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.
- Naming without the suffix, or naming the location.
BadThingandImportServiceErrorboth fail the test. Name the condition and end withException:MalformedRowException,InsufficientFundsException.
Best Practices
- Create a custom type only when a handler will
catchit by name or read data off it; otherwise use a built-in type with a precise message. - Derive from
Exception, keep the classpublic, andsealthe 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.Datafor 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
Adviceon your base type to force each new failure to explain its own remedy. - Skip
[Serializable]and theSerializationInfoconstructor in new code; carry failures across process boundaries as data, not as live exception objects.
Practice Exercises
- Name a failure. Write
OutOfStockExceptionwith an immutableRequestedandAvailable(bothint) and a message built from them. Throw it from anOrder(int quantity)method and catch it inMain, printing how many units the customer would have to remove to succeed. - Preserve the cause. Write
ConfigurationException(string key, Exception inner)and throw it from a method that callsint.Parseon a bad setting value. In the handler, printex.Message, thenex.InnerException!.GetType().Name, then walk the whole chain in awhileloop untilInnerExceptionisnull. - Build a family. Create an abstract
ShippingExceptionwith two sealed subclasses (AddressUnknownException,ParcelTooHeavyException), each with one property of its own. Write onecatch (ShippingException)that prints a common line, and prove both subclasses land in it. - Refactor the code enum. Take a single exception class that carries
ErrorCode Code { get; }and threewhenfilters, and split it into three types plus a shared base. Compare the twocatchsections and write down which one a new team member would understand faster, and why.