A recent Daily WTF explored a Guard class which throws an ArgumentNullException if a parameter is null. Most of the commenters correctly point out that the code is not a WTF but rather a good practice because it
- Enforces the code contract - this parameter is not allowed to be null
- Provides better stack trace information
- Causes the app to fail fast
One principle at work here is the idea of adding information to an exception. Without guarding against potentially invalid input in this situation, a NullReferenceException will (presumably) be thrown at some point. But why? What's null? What made it null? Even with the stack trace, this can be painful to debug... annoying at the least. An ArgumentNullException cuts straight to the problem and tells us exactly what is wrong. Anytime you can add information to an exception (or potential exception in this case), you should do it*.
I think this is a good principle to follow when deciding whether or not to catch an exception (that you can't recover from) as well. If you can add information by wrapping it in a more specific exception and adding contextual information, you should do so. Otherwise, there's no need to handle and re-throw.
*Well, not if might expose implementation details you want to hide from users.
Comments