If you're writing a BigInteger library, then you absolutely should throw an appropriate DivideByZero
exception. If you're writing a shopping-cart library, then...eh, probably not.
I can't, at the moment, think of a good reason to throw a NullReferenceException
. If you're create an API with documentation that says "The first parameter to HummingBirdFeeder.OpenSugarWaterDispenser(Dispenser dispenser, int flowRate)
is the sugar-water dispenser that you wish to open." And if somebody then comes along and passes a null value to this method, then you should definitely throw an ArgumentNullException
.
Letting a NullReferenceException
out of your API would just be lazyness, though, because that's wrong and it leaks some of your internals.
EDITED TO ADD:
Now that you changed the question to refer to an ArgumentNullException
then the answer is easy: yes, you should definitely throw that kind of exception under these circumstances:
- You are writing a public method.
- Getting a null value for the argument is in some way inappropriate (i.e., the method makes no sense without that particular argument).
- The documentation for the method indicates that null values are not allowed.
In that case, the very first thing your method should do is check for a null value and throw an exception if the condition is violated.
If you are writing a private or internal method, then in most cases you would not need to validate the parameters at runtime in the release build. You can make sure that your own code calls your own code correctly. One thing that helps to create that assurance is to validate the parameters in the debug build by adding assersions:
Debug.Assert(dispenser != null);
This way you can verify that the code is acting correctly and catch any errors earlier without slowing down the released code with a bunch of useless, redundant checks.