When to use Custom Exceptions?

When to use Custom Exceptions?


A conversation I recently had on the DDD-CQRS-ES slack channel got me thinking about custom exceptions and when to use them. Up until this point I’ve always considered it best practice to define custom exception instead of using the the standard exceptions supplied by the dotnet framework.

For example:

private Meta GetMeta(EventMessage message)
{
    if (!message.Headers.ContainsKey("Meta"))
    {
        throw new MissingMetaHeaderException(message.Body);
    }

    return (Meta)message.Headers["Meta"];
}

public class MissingMetaHeaderException : Exception
{
    public MissingMetaHeaderException(object e)
        : base($"{e.GetType().FullName} is missing the meta header")
    {
    }
}

Instead of throwing an InvalidOperationException or similar. The reason for doing this is so that it makes it easier to catch specific exception types within your code. But what happens if the exception you are throwing is a “human caught” exception (One that is passed all the way back to the user).

In this scenario is there any point in creating a custom exception? I’m not so sure any more. Would it not just be better to use one of the standard exception types and make sure the message is clear enough to indicate what the problem is?

if (!message.Headers.ContainsKey("Meta"))
{
   throw new NullReferenceException($"{e.GetType().FullName} is missing the meta header");
}

Also with the new exception filters in c# 6 allowing us to catch exceptions based upon information with exception its self its possible we could further avoid creating more custom exceptions.

catch (ArgumentException e) when (e.ParamName == “…”)
{
}

I’m not sure what approach I’ll take in the future. Either way its got me thinking…