C#: Throwing Custom Exception Best Practices

Based on my experience with libraries, you should wrap everything (that you can anticipate) in a FooException for a few reasons:

  1. People know it came from your classes, or at least, their usage of them. If they see FileNotFoundException they may be looking all over for it. You’re helping them narrow it down. (I realize now that the stack trace serves this purpose, so maybe you can ignore this point.)

  2. You can provide more context. Wrapping an FNF with your own exception, you can say “I was trying to load this file for this purpose, and couldn’t find it. This hints at possible correct solutions.

  3. Your library can handle cleanup correctly. If you let the exception bubble, you’re forcing the user to clean up. If you’ve correctly encapsulated what you were doing, then they have no clue how to handle the situation!

Remember to only wrap the exceptions you can anticipate, like FileNotFound. Don’t just wrap Exception and hope for the best.

Leave a Comment