Modern C# Development: Custom Exceptions Made Simple
Source: Dev.to
Introduction
Errors happen. Sometimes they are simple, and sometimes they are very specific to your domain. C# provides many built‑in exceptions, but they don’t always tell the full story. Custom exceptions let you convey domain‑specific problems clearly.
When to Use a Custom Exception
Consider an ordering system where a user tries to place an order that violates business rules.
throw new InvalidOperationException("User cannot place this order");
The built‑in exception works, but the message is generic. A custom exception provides more context:
throw new OrderNotAllowedException(userId);
Defining a Basic Custom Exception
A custom exception is simply a class that inherits from Exception.
public class OrderNotAllowedException : Exception
{
public OrderNotAllowedException(string message)
: base(message)
{
}
}
This minimal version is enough to get started.
Adding Contextual Information
Instead of packing everything into the message string, expose relevant data as properties.
public class OrderNotAllowedException : Exception
{
public Guid UserId { get; }
public OrderNotAllowedException(Guid userId)
: base($"User {userId} is not allowed to place an order")
{
UserId = userId;
}
}
Now logs and error handlers can access UserId directly, eliminating the need for string parsing and simplifying debugging.
.NET Version Considerations
In older .NET versions (e.g., .NET Framework 4.x and earlier), you often added extra constructors for serialization. With modern .NET (Core, 5+, 6+, 7+), the simple class shown above is sufficient.
Avoid Overusing Custom Exceptions
Custom exceptions are useful, but they can be misused. Try to avoid:
- Using exceptions for normal control flow
- Creating very generic custom exceptions that add no value
- Exposing internal exception details from public APIs
If a built‑in exception already describes the problem well, prefer it.
Guideline Checklist Before Creating a Custom Exception
- Does this represent a real exceptional case?
- Does it add meaning beyond a simple message string?
- Does the name clearly describe the problem?
If the answer is yes to all three, a custom exception is a good fit.
Conclusion
Custom exceptions are a small feature that can make your code clearer and easier to maintain. When used appropriately, they tell a concise story about what went wrong and why.