The Well-Tempered Exception

A few months, I was writing some code and I came across an Exception class that didn't work the way I expected. I wanted to catch an exception and then wrap it in an exception of the same type. However there wasn't a constructor that took an exception, so I couldn't do it. In other words, the class designer hadn't included the (string message, Exception inner) constructor. This got me thinking about how exception classes should be written, and I realized that I didn't understand exactly what the rules were. After doing a little research?and writing a little code?I figured out the proper way to write exception classes. I also determined that it's easy to make mistakes when writing exception classes. Therefore, I've decided to spend this month talking about the design of exception classes and presenting a utility that validates the design of exception classes. Is a New Exception Required? The .NET Framework has a number of general-purpose exceptions that you can use in your code. If you determine that an argument has a null value, for example, you can throw an ArgumentNullException. If an existing exception isn't a good match, you should write your own exception class. A Basic Exception Once you've decided to create a new exception, you need to name it. Try to come up with a name that conveys the reason the exception is thrown. All exception classes should end in the word Exception, and should be derived from the class ApplicationException. While this isn't a strict requirement and nothing will break if you don't do this, doing so makes it easier for people to maintain your code. So, the basic outline of an exception class is as follows:

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish