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. Howeve

ITPro Today

February 17, 2002

1 Min Read
ITPro Today logo in a gray background | ITPro Today

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 ExceptionOnce 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:

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like