skip to content

In C#, when does a library earn its own exception type such as CarrierUnavailableException, and how should that class be declared?

level: middleimportance: should knowfreq 45%

answer

  1. would a caller catch it differently
  2. derive from Exception directly
  3. three public constructors
  4. extra data as read-only properties
  5. serialization constructor is obsolete

basics

~20 s

A custom exception earns its place when callers must catch that failure separately or read data no built-in type carries. Derive it from Exception, end the name in Exception, make it public, and give it the three standard constructors.

solid answer

~40 s

First check whether a built-in type already says it: bad arguments are the `ArgumentException` family and a wrong state is `InvalidOperationException`. A custom type earns its place when callers will handle that failure differently from everything else, such as a quote service showing "try again later" for `CarrierUnavailableException`, or need data like a `CarrierCode` property. Derive from `Exception`, not `ApplicationException`; end the name in `Exception`; keep it `public` (CA1064); and declare the three constructors CA1032 asks for: `()`, `(string message)` and `(string message, Exception innerException)`. The last one is what lets you wrap a lower-level cause. Expose extra data as read-only properties and include it in an overridden `ToString`. Since .NET 8 the `(SerializationInfo, StreamingContext)` constructor is obsolete (SYSLIB0051), so a new type leaves it and `[Serializable]` out.

code

csharp · 18 lines
csharp
#:property AnalysisMode=All
try
{
    throw new CarrierUnavailableException("PARCEL-EU", "Carrier PARCEL-EU is unavailable.");
}
catch (CarrierUnavailableException e)
{
    Console.WriteLine($"{e.CarrierCode}: {e.Message}");
}

// Only one constructor, so there is no way to pass an inner exception.
public sealed class CarrierUnavailableException : Exception
{
    public CarrierUnavailableException(string carrierCode, string message) : base(message)
        => CarrierCode = carrierCode;

    public string? CarrierCode { get; }
}

go deeper

for a junior

Recall the recipe: derive from Exception, end the name in Exception, add the parameterless, message, and message-plus-inner constructors.

for a middle

Explain when a built-in type is enough, why the inner-exception constructor matters, and what CA1032 and CA1064 report. Know that the serialization constructor is obsolete since .NET 8.

for a senior

Justify each custom type by a caller that catches it and acts differently, and treat its properties and base type as public API that cannot change freely.

for a principal

Decide between one sealed type per failure and a small catchable hierarchy for the library, weighing caller simplicity against the cost of every type becoming a versioned contract.

## Start with the built-in types The .NET guidance is to introduce a new exception class **only when a predefined one does not apply**. Most failures in a library are already named by the base class library: - a bad argument: `ArgumentNullException`, `ArgumentOutOfRangeException`, `ArgumentException`; - a call in the wrong object state: `InvalidOperationException`, or `ObjectDisposedException` after disposal; - an operation the type does not support: `NotSupportedException`; - text in the wrong format: `FormatException`. A custom type that merely restates one of these, such as an `InvalidWeightException` for a negative weight, adds a type to learn and catch without adding information. ## When a custom type earns its place - **Callers will handle it differently.** A service calling a shipping-quote library shows "try again later" when the carrier is down, but treats a bug as a 500. That needs a type it can catch on its own: `CarrierUnavailableException`. - **Callers need data the message cannot carry reliably.** Parsing a message string is fragile; a `CarrierCode` property is a contract. `FileNotFoundException.FileName` is the BCL's own example. - **A layer needs its own vocabulary.** A boundary translates low-level failures such as `HttpRequestException` into the library's terms, keeping the original as the inner exception. A useful test in review: name the caller that has a `catch` for this type and says what it does there. If nobody would catch it specifically, a built-in type is enough. ## How to declare it ```csharp public sealed class CarrierUnavailableException : Exception { public CarrierUnavailableException() { } public CarrierUnavailableException(string message) : base(message) { } public CarrierUnavailableException(string message, Exception innerException) : base(message, innerException) { } public CarrierUnavailableException(string carrierCode, string message, Exception innerException) : base(message, innerException) => CarrierCode = carrierCode; public string? CarrierCode { get; } public override string ToString() => $"{base.ToString()}{Environment.NewLine}Carrier: {CarrierCode}"; } ``` 1. **Derive from `Exception`** (or from a more specific existing exception when yours is a special case of it). The guidelines say not to derive from `ApplicationException`. 2. **End the name in `Exception`.** 3. **Declare the three standard constructors.** CA1032 lists them as `public NewException()`, `public NewException(string)` and `public NewException(string, Exception)`. Without the last one nobody can create your exception with a cause attached. 4. **Make it `public`.** CA1064 reports a non-public exception derived directly from `Exception`, `SystemException` or `ApplicationException`, because outside its assembly callers could only catch it as the base type. 5. **Add read-only properties** for the extra data, set through extra constructors, and override `ToString` so logs show them. 6. **Write messages as sentences** ending in a period, without sensitive data. Keep all three standard constructors even when the library itself only ever calls the richer one. Other code constructs your exception too: a test double that simulates an outage, a caller's adapter that rethrows it with more context, or a later layer that needs to attach a cause. The parameterless and message-only constructors cost two lines each, and omitting them is exactly what CA1032 reports. ## What the analyzers check | Rule | What it reports | Reported by default in .NET 10 | |---|---|---| | CA1032 | A missing standard constructor | No | | CA1064 | A non-public exception derived directly from a base exception type | No | | CA2201 | Throwing `Exception`, `ApplicationException`, `SystemException` or a runtime-reserved type | No | | SYSLIB0051 | Calling the legacy serialization constructor, for example `: base(info, context)` | Yes, an obsoletion warning since .NET 8 | With `AnalysisMode=All`, a class that declares only `(string carrierCode, string message)` gets three CA1032 warnings, one per missing constructor, each naming the exact signature to add. ## Serialization is no longer part of the recipe Older guidance added `[Serializable]`, a `protected (SerializationInfo info, StreamingContext context)` constructor and a `GetObjectData` override. In .NET 8 those APIs became obsolete with diagnostic **SYSLIB0051**, because exception serialization existed for .NET Framework remoting, which .NET Core never supported. A new exception type leaves all three out; the SYSLIB0051 page explains how a library that must keep them for API compatibility marks its own copies obsolete. ## A hierarchy or a sealed class `sealed` is a reasonable default for a single failure: callers cannot depend on subclasses you never designed. When several failures share handling, a small hierarchy works better: an unsealed `QuoteException` base with `CarrierUnavailableException` and others derived from it lets a caller `catch (QuoteException)` for the family or the derived type for one case. Either way the types and their properties become public API, so adding, renaming or re-parenting one later is a breaking change for every caller that catches it.

  • Why does CA1032 insist on the (string message, Exception innerException) constructor?
    It is the only way to create your exception with a cause attached. Code that catches a lower-level exception, say an `HttpRequestException`, and translates it into your type needs to pass the original as `innerException` so `InnerException`, `GetBaseException()` and `ToString()` keep the real cause and its stack trace. Without that constructor, wrapping loses the original.
  • Should a new custom exception still be marked [Serializable] with a serialization constructor?
    No. Since .NET 8 the `Exception(SerializationInfo, StreamingContext)` constructor and `GetObjectData` are obsolete with SYSLIB0051, because exception serialization served .NET Framework remoting. New types omit `[Serializable]`, the constructor and the override; only a library bound by API compatibility keeps them and marks its own copies obsolete.

  • Creates a custom exception for every distinct error message
  • Derives custom exceptions from ApplicationException
  • Declares only a message constructor, so a cause cannot be attached
  • Makes the exception internal although it escapes the assembly
  • Adds a SerializationInfo constructor to every new exception on .NET 8 or later