.NET Exceptions – common exceptions and usage guidelines
August 9, 2009 § Leave a comment
My earlier post containing a list of all .NET exceptions gets a lot of traffic. It’s a great reference, but it’s also a really large list and doesn’t give much guidance regarding how to use them. This post will try to give some guidance regarding the more commonly used exceptions and in what circumstances they should be used.
Generally speaking, if you need to throw an exception purposefully, you should probably define a custom exception for that (read the bit about ApplicationException below). There are only a few of the built-in .NET exceptions that you’ll ever want to throw. Here’s my top 5 or so.
The exception that is thrown when a non-fatal application error occurs.
The ApplicationException was originally intended as a base class for application specific exceptions. In other words, you’d derive from ApplicationException rather than Exception for any application specific exception types you needed to define. In practice, most developers don’t seem to do this. Honestly, I don’t know if it’s because they aren’t aware of it, or because it doesn’t really convey any particular benefits.
The obvious benefit of using this class is that if you have multiple application specific exceptions you want to define, and you do derive them all from ApplicationException, you can just catch the base class upstream and handle it. If you’re using a construct like the Microsoft Enterprise Library Exception Handling Application Block, this can come in very handy.
The exception that is thrown when one of the arguments provided to a method is not valid.
This is a really handy exception that I use all the time. However, you should preferentially use one of the below exceptions. In other words, don’t do something likethrow new ArgumentException("parameter1 is null.");
when you could do something likethrow new ArgumentNullException("parameter1");
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.
The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.
The exception that is thrown when a requested method or operation is not implemented.
This is a great exception that seems to hardly ever get used. Even some of the stuff that Visual Studio will generate automatically will do something likethrow new Exception("Method is not yet implemented.");
instead ofthrow new NotImplementedException();
This obviously isn’t all of them, but it’s a start. The few exceptions I listed above, in combination with custom application-specific exceptions, account for about 90% of the exceptions I ever have to throw.