Skip to content
Tutorials Center
My learning

Topics

Lesson 86 of 182 ยท Null Safety and Errors

Custom Exceptions and Exception Design

Learn to write custom exception classes in C#, add data, chain InnerException, handle AggregateException, decide between throwing and returning errors, and use guard clauses like ThrowIfNull.

The built-in exceptions describe technical failures: a bad argument, a missing file, a wrong state. Your application has its own failures, expressed in the language of your domain: "insufficient funds", "order already shipped", "seat already booked". You can give those failures their own exception types. A well-designed custom exception makes the calling code clearer (catch (InsufficientFundsException) says exactly what is handled) and can carry the data needed to react: how much was missing, which seat, which order.

Just as important is knowing when not to create one, and when to avoid throwing at all. This lesson shows how to write an exception class correctly, how to nest exceptions with InnerException, what an AggregateException is, how to decide between throwing and returning an error value, and how to write guard clauses that fail fast.

A first custom exception

A custom exception derives from Exception (not ApplicationException, which is a legacy base with no benefits) and its name ends with Exception.

C# InsufficientFundsException

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 class is five lines, yet the catch now reads like a sentence and the handler can use Shortfall to tell the user exactly what is missing. Compare that with throwing new Exception("Insufficient funds"): callers would have to parse the message text to react, which breaks the moment someone fixes a typo.

The conventional constructors

The framework's own exceptions offer three constructors, and a public exception type that others will use should too:

  1. a parameterless one,
  2. one taking a string message,
  3. one taking a string message and an Exception innerException.
C# A complete custom exception type

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.

For an exception that is only used inside one small program, a single useful constructor is enough. The standard trio matters for libraries, serializers and code that creates exceptions generically.

Old tutorials add a protected constructor with SerializationInfo and mark the class [Serializable]. That was for BinaryFormatter, which was removed from modern .NET because it is insecure. In current code you do not need either.

Design guidelines

  • Name it for the problem, in the domain's words: PaymentDeclinedException, not MyException or ErrorException.
  • Make the data first-class (properties like Shortfall or OrderId), and keep them read-only.
  • Write a message for developers: what happened and what value caused it. The user-facing text is a separate concern, shown by whoever catches it.
  • Keep the hierarchy shallow. A common base class per library (PaymentException) with a few children lets callers catch broadly or narrowly. Deep trees are rarely worth it.
  • Do not create exception types nobody will catch separately. If every handler just logs and gives up, InvalidOperationException with a clear message is enough. Prefer reusing ArgumentException, InvalidOperationException, NotSupportedException when they honestly describe the problem.
  • Do not put secrets (passwords, tokens, personal data) in messages; they end up in logs.

Exception chains: InnerException

Low-level failures should be translated into the level your caller understands, without losing the cause. Pass the original as innerException, then walk the chain when diagnosing.

C# Translating a low-level failure and walking the chain

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 class ReportException uses a primary constructor (C# 12) that passes both values to the base class, which is the shortest way to write an exception when no extra members are needed. The caller sees the high-level message first and still has all the evidence underneath. Printing e.ToString() also includes the inner exceptions and their stack traces.

AggregateException

Sometimes several things fail at once, as when you run many tasks in parallel. .NET collects the failures into an AggregateException whose InnerExceptions property lists them all. You will meet it mainly with Task.WaitAll, Task.Wait() and Parallel methods; await unwraps it and rethrows the first inner exception, which is one reason async code is easier (see Tasks and the Task Parallel Library).

C# Collecting several failures

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.

Do not rely on the order of InnerExceptions, which can depend on timing; we sorted the messages to keep the output stable. When handling an aggregate you can call ae.Flatten() to remove nesting, or ae.Handle(e => ...) to handle some of the inner exceptions and rethrow the rest.

Throw or return an error?

Exceptions are for the situations a method cannot meet its contract and the caller probably cannot continue normally. They are a poor tool for expected outcomes. The cost is two-fold: throwing is slow (microseconds against nanoseconds), and an exception is invisible in the method signature, so callers forget to handle it.

Situation Better approach
User types invalid text into a number field int.TryParse, validation result
Dictionary key might be missing TryGetValue
Searching: "not found" is normal return null or Try..., or an empty list
A rule of the domain is violated by caller bug throw
An invariant is broken, I/O failed, state is corrupt throw
Argument is null or out of range throw (guard clause)

A useful test: if this happens 1,000 times a second in a healthy system, should it be an exception? If yes to "it happens", it should not be one.

C# TryParse versus exception: both work, one is meant for this

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.

Guard clauses

A guard clause checks a precondition at the top of a method and fails immediately if it is not met. This keeps the real logic unindented and puts the error close to the cause. The .NET base class library has static helpers for the common checks, so each guard is one line:

C# The ThrowIf family

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 available helpers include ArgumentNullException.ThrowIfNull, ArgumentException.ThrowIfNullOrEmpty / ThrowIfNullOrWhiteSpace, and for numbers ArgumentOutOfRangeException.ThrowIfNegative, ThrowIfZero, ThrowIfNegativeOrZero, ThrowIfGreaterThan, ThrowIfLessThan and friends. They record the argument name automatically, and ObjectDisposedException.ThrowIf(condition, this) covers disposed objects. The null operators lesson showed ThrowIfNull and friends in context: Null-Handling Operators.

Guard public members; internal helpers can trust their callers. For argument errors throw the argument exceptions with the right ParamName; for "this object is in the wrong state right now" throw InvalidOperationException; for "this operation can never work on this type" throw NotSupportedException.

Where to catch

Catch where you can do something: retry, show a message, choose a fallback, roll back. Do not wrap every method in try/catch. A typical application has a few well-chosen handlers: one near each user action or request and one at the top that logs and shows a friendly error. Everywhere else the exceptions pass through freely, and finally/using handle the cleanup. Choosing filters for those top-level handlers is the subject of Exception Filters and Error Handling Patterns.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which base class should a new custom exception normally derive from?

    Derive from Exception (or a more specific base in your own hierarchy). ApplicationException offers no benefit and SystemException is for the runtime itself.
  2. 2. Why pass the original exception as innerException when you throw a higher-level one?

    The inner exception keeps the evidence of the real failure, and ToString and logging show the whole chain.
  3. 3. A user types "abc" into a field that expects a number. What is the best approach?

    Bad user input is an expected outcome, not an exceptional one. TryParse is cheaper and makes the failure visible in the code.
  4. 4. What does an AggregateException contain?

    It wraps several exceptions, for example from parallel tasks, in InnerExceptions.
  5. 5. Which guard clause correctly rejects a null or blank title in modern .NET?

    ThrowIfNullOrWhiteSpace throws ArgumentNullException for null and ArgumentException for empty or whitespace, with the parameter name filled in.

Summary

  • Custom exceptions derive from Exception, are named ...Exception, and carry domain data as read-only properties.
  • Provide the standard constructors (none, message, message plus inner exception) for public types; a primary constructor is a compact option.
  • Always pass the cause as innerException when translating errors, so the whole chain survives.
  • AggregateException collects several failures; use InnerExceptions, Flatten and Handle.
  • Throw for broken contracts and invalid state; use TryXxx methods and return values for expected outcomes.
  • Use the ThrowIf... guard helpers at the top of public methods and catch only where you can act.

Next: Exception Filters and Error Handling Patterns