When should you create a custom exception type?

C# Error Handling Intermediate 2–3 Yrs3–5 Yrs Conceptual 1 min read

Quick Answer

Create a custom exception when callers need to catch that specific failure and handle it differently — a PaymentDeclinedException vs a generic error. Add properties carrying the context (the declined amount, the order id). Don't create one for every method; reuse framework exceptions (ArgumentException, InvalidOperationException) where they fit.

The test is whether a caller would want to catch this specific thing and do something different. If a payment being declined needs a different response than a network error, then PaymentDeclinedException earns its place, and I'd put the relevant data on it as properties. But I don't make a new exception per method — for bad arguments or invalid state, the built-in ArgumentException and InvalidOperationException already say what I mean. And in a web app I map my custom exceptions to status codes in one central handler rather than catching them everywhere.

  • Derive from Exception (not the obsolete ApplicationException); provide the three standard constructors.
  • A small domain-exception hierarchy (DomainException → OrderException) lets a handler catch broadly or narrowly.
  • Exceptions are for exceptional conditions, not control flow or expected validation results.
  • Map custom exceptions to HTTP status codes in one place (an exception handler / middleware).