Are there any Exceptions defined in the .NET Framework that I shouldn't throw in my own code, or that it is bad practice to? Should I write my own?
You shouldn't throw any exception that is automatically thrown by the CLR due to user errors. For instance
The reason being is to do so creates confusion for people calling your API. Users should be able to distinguish between actively thrown exceptions by an API and exceptions that are not actively thrown (thrown by CLR).
The reason is that at actively thrown exception generally represents a known state in an API. If I call an API and it throwns an ArgumentException, I have a reasonable expectation that the given object is in a good state. It recognized a potentially bad situation and actively accounted for it. On the other hand if it throwns a NullRefrenceException, that is an indication that the API encountered an unknown error and is now in an unreliable state.
Another lesser reason is that these exceptions behave differently when thrown by user code as opposed to the CLR. For instance it's possible to catch a StackOverflowException if thrown by user code, but not if it's thrown by the CLR.
EDIT Responding to Michael's comment
You also should not throw Exception, ApplicationException or SystemException directly. These exceptions types are too general to provide meaningful information to the code which calls your API. True you can put a very descriptive message into the message parameter. But it's not straight forward or maintainable to catch an exception based on a message. It's much better to catch it based on the type.
FxCop rule on this subject: http://msdn.microsoft.com/en-us/library/ms182338(VS.80).aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With