Using guard methods to anticipate errors when exceptional inputs are passed

I tend to vocalize (read: harp) on guard methods quite regularly, and given the debugging session I just completed, it is fresh on my mind.

So here goes:

Please, please, please check your inputs as soon as you can, before system-generated exceptions occur. It is better to fail as soon as you know something is wrong than to pass bad data forward and break your user’s state. Also, if you pass good information back to your caller, debugging is a much more time-effective endeavor.

If you have a method and you expect a value to be passed in, check that it is passed in. Even better (when it makes sense to,) check that it has a valid value (see the second method.) Guard methods allow you to do all of this.

For this purpose, I first use this method, which throws an ArgumentNullException if input is null:

As you can see, this is written as an extension method on the object class, so it can be called on any input, given you have imported the containing namespace. This allows you to write code like this:


Now, if we also want to check that a valid value has been passed, we can use this method:

And call it like so:

You’ll notice that this example includes a string (with a specified default value of string.Empty and an enum ( PartFinderType) with a default value of PartFinderType.None. This lets you define what you consider to be a default value that you do not want to allow.

So why is any of this useful, you ask?

Isn’t throwing an exception just going to make my application break? Yes, it is. But (in ASP.NET) it turns an exception like this:

NullReferenceException yellow screen (no guard method)



Into something useful and informative like this:

ArgumentNullException yellow screen with parameter name (guard method)



Not only that, it also throws the exception as soon as the exceptional state is detected (instead of waiting until the object is accessed, possibly much further down the call stack) and gives a meaningful exception (and message) to the caller so they can fix their call.

Please take this to heart and use some sort of guard methods when coding. It will save you and anyone consuming your methods a lot of headache down the road.

Now, to hunt down the cause of this uninformative exception I encountered today…

Leave a Reply

Your email address will not be published. Required fields are marked *


1 × two =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">