Custom Exceptions: When should you create them?

I think the best answer is: rarely.   It’s really hard to go straight to a justification here though.  I find that answering a different question will eventually shed led on when to create a new exception.

"What are the benefits of creating a new/custom exception?"

The answers I come up with or have heard before are …

  1. Provides a type safe mechanism for a developer to detect an error condition. 

    Without a custom exception a developer would be forced to compare an existing value on an existing exception class in order to determine if a particular error occurred.  To ensure this was unique across applications and environments a unique identifier would need to be inserted as well (likely a GUID).  The resulting code would be quite ugly and maintainability would be a question mark. 

  2. Add situation specific data to an exception

    Ideally this data would help another developer track down the source of the error.

    But an entirely new exception is not needed to achieve this goal. The base Exception class contains a property named Data which is an open dictionary. Any code which raises an exception is free to add custom data into the exception. This data can then be accessed by the handling code. Unique values still need to be dealt with. But in my experience, accessing a GUID based custom property is a bit more accepted than catching an exception based on some GUID property.

    This is especially true now with extension methods. The lack of type safety in the dictionary and potentially constant string sharing for property names could be hidden inside an extension method

  3. No existing exception adequately described my problem

    I’d argue against this because of InvalidOperationException. Invalid operation should cover most exceptional cases

So of these reasons only #1 is a stand alone benefit of a new exception.  Now lets re-state this advantage in the context of the original question.

Creating a new exception allows a developer to catch them

Simple right?  But what benefit does this give to a developer?  From my experience there are only two reasons to catch an exception. 

  • It’s a particular for which the underlying exceptional problem can be corrected.  Perhaps the user is prompted to fix the condition by performing some outside action (like re-inserting a disk).
  • Logging errors for post-mortem debugging.  Note: You could also use the Data dictionary and extension methods above to introduce a new method ShouldLog().  This would allow you to avoid creating a new exception type. 

Now I think we can answer the original question of this blog post.

You should only create a new exception if you expect developers to take corrective action for the problem or to log for post mortem debugging.

Otherwise, what benefit does creating this exception give you?

Comments (5)

  1. Jason M says:

    Thinking about custom exceptions I’ve made in the last few months, I think all of them fall under the "it’s a particular exception for which the underlying exceptional problem can be corrected." Things like parsing a configuration file failed (so I can notify the user of their syntax error), errors in a network stream that mean that a packet was dropped and you should reconnect, etc. Use of exceptions simply makes the code cleaner. But at this point using a custom exception is neccesary, since using a "generic" one IMHO is a risk because you might catch something that indicates an unrelated problem.

  2. gOODiDEA.NET says:

    .NET New .NET Logos announced today! – ASP.NET Patterns every developer should know Writing a simple

  3. gOODiDEA says:


  4. Greg says:

    Never create custom exceptions.  Follow the .NET evolution from 1.0 to 2.0 by returning useful values from function calls you write instead of throwing exceptions (see the file and directory .NET api changes).

    We learned through years of C++ usage that custom exceptions are nice in theory but add greatly to code bloat and maintainablity cost over the long term.

  5. @Greg

    I assume in the first paragraph you’re referring to the Int32.Parse style API’s to Int32.TryParse.  This represents a similar but different class of issues.  This was largely done for performance reasons because users wanted to call these APIs in a loop with lots and lots of data (good and bad data).  The underlying problem is correctable (misformatted strings can be re-prompted or ignored) weren’t a bad choice for a custom ecxeption.  But given this is also an incredibly simple operation so an exception is a bit heavy handed.

    I disagree with your second assertion on both counts.  IMHO they greatly reduce code bloat.  Take COM programming for an example.  Most COM programs are riddled with IfFail* calls.  Every one of these expands to a conditional/jump operation which greatly increases code bloat since the vast majority of the time the error condition doesn’t happen (it is quite frankly unreadable).

    The second part about maintainability.  I personally find that exceptions are much more maintainable that traditional error handling.  Lets go back to COM for instance.  90% of all COM code I’ve dealt with have the exact same pattern

    1) Declare HRESULT at top of function

    2) Declare Error: label at the end of the function

    3) Make every call IfFailGo()

    The maintainability problem here is every single error is handled in the exact same way.  There is no way for a future coder down the line to look at that code and understand what errors are 1) valid, 2) fatal 3) somewhere in between.  With exceptions it’s a bit clearer what errors were at least intended to be handled.  

    Exceptions can be abused to make maintainability an issue.  But that should be dealt with on a case by case basis.