Hi lovely readers,
Errors happen. Sometimes they are simple, and sometimes they are very specific to your domain. C# gives us many built in exceptions, but they do not always tell the full story. That is where custom exceptions come in.
In this post, we are going to look at how to create your own custom exceptions in C#. We will keep it simple, practical, and easy to use in real projects.
Why custom exceptions exist
Imagine you are building an ordering system. A user tries to place an order, but the business rules say no. You could throw something like this:
throw new InvalidOperationException("User cannot place this order");
This works, but it does not say much. Later on, when you read logs or handle errors, you have to rely on the message string.
Now compare it to this:
throw new OrderNotAllowedException(userId);
This tells a clear story. Something specific went wrong, and it belongs to your domain.
Creating a basic custom exception
A custom exception is just a class that inherits from Exception.
Here is the smallest useful version:
public class OrderNotAllowedException : Exception
{
public OrderNotAllowedException(string message)
: base(message)
{
}
}
That is all you need to get started.
Adding useful information
The real power of custom exceptions comes from adding context. Instead of putting everything into the message, you can add 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 your logs and error handlers can access UserId directly. No string parsing needed. This makes debugging much easier.
Do you need serialization constructors
In older .NET versions (.NET Framework 4.x and earlier), you often saw extra constructors for serialization. If you are using a modern version of .NET, a simple exception class like the ones above is enough.
When not to create custom exceptions
Custom exceptions are useful, but they are easy to overuse.
Try to avoid these situations:
- 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, use it.
A quick checklist
Before creating a custom exception, ask yourself:
- Does this represent a real exceptional case
- Does it add meaning beyond a message string
- Does the name clearly describe the problem
If the answer is yes, a custom exception is a good fit.
That is a wrap
Custom exceptions are a small feature, but they can make your code much clearer and easier to maintain. Used well, they tell a story about what went wrong and why.
I hope this post gave you a quick introduction to creating your own exceptions in C#. If you have thoughts or questions, feel free to leave a comment or find me on my socials.
See ya!
Top comments (0)