Recently I have argued with one of my fellow developers. On the topic was the point of validating input parameters for null values. The standard practice is for a null valued parameter (that we do not expect to be null) to throw some kind of exception: ArgumentNullException - most likely. But what if we don’t check the parameter and let the execution flow? It is possible that in the few instructions, the null reference exception will occur.
Now what is the difference between those two kinds of exception? Ultimately both signal that something went in an unexpected way. they both halt the execution of the code etc. Why bother?
There are numerous reasons why you should bother some of them include:
- ArgumentNullException is way more meaningful when it comes to finding out the cause of the problem. For one, it allows you to specify the name of the parameter - something the automatically thrown NullReferenceException does not.
- Throwing earlier saves both memory and processor time since if ultimately we are going to get the exception it is better to get it before executing some possibly time consuming sub-routine. Additionally it is easier to rollback since there is nothing to rollback :-).
- It is easier to debug the code. It is just a single line where you throw “connection cannot be null”. Compare this to a line where there are multiple instructions invoked as it often happens and you wonder which one of the calls caused the exception.
- What are you going to tell the author of the component if you happen to not have the stack trace for the exception - just message? That their component is not good :-P.
- I personally believe that it is a shame then one of my methods throws a null reference exception.
In the extreme case, you could want to forget about exceptions altogether but what would you say if .NET Framework was written in such a way? You wouldn’t be happy yes?
As for the very good description of how you should handle exceptions I suggest reading the chapter on exceptions in Jeffrey Richter’s book.