Click here to Skip to main content
Licence MIT
First Posted 12 Dec 2004
Views 77,468
Bookmarked 35 times

I take exception to that argument!

By | 30 Dec 2004 | Article
Achieve greater consistency in raising argument exceptions with very little effort. This utility class (which is covered by nearly 600 included NUnit test cases!) makes it possible to evaluate and raise exceptions on passed-in parameters, using a single line of code.

Introduction

Admit it: you’re probably more lax than you should be about parameters that get passed into the class members you write. Laziness strikes every developer from time to time. I myself got tired of typing the following code every other minute:

    if (value == null)
        throw new ArgumentNullException("value");

I got lazy enough that I decided to make testing member arguments and raising exceptions on them as effortless as possible. The result of my laziness is a utility class that makes it easy to be strict about what you allow callers to pass into your code.

Since this code is likely to be of use in every part of most of your C# projects, I also went to the trouble of writing nearly 600 NUnit test cases that you can run to verify my code’s correctness and to get a feel of how to call this utility class from your code. (See Testing the code below, for information on how to run the test cases.)

Using the code in your projects

This utility class is designed to be included in your C# projects, not referenced as a compiled assembly. The reasons for this should be obvious, but you definitely don’t want dozens of copies of a C# source file all over your source tree. So put the file in the root of your source code directory and make a link (see below) to that one file in each of your C# projects.

linking to a single copy of Exceptions.cs in Visual Studio

Exceptions.cs has nine static methods (most of them heavily overloaded) that test for argument constraint violations and throw the appropriate standard argument exception. The methods are thoroughly documented in XML documentation comments within the source and in an HTML Help file generated from those comments. Examples are included in the documentation to show how the methods can be used most effectively in your code—everything from implementing IComparable, to extending CollectionBase, to argument validation in constructors, methods and properties. Briefly summarized, the methods are:

  • ThrowIfDifferentRank() throws RankException if an array argument does not have a given number of dimensions.
  • ThrowIfDifferentType() throws ArgumentException if an argument is not an instance of a given type.
  • ThrowIfIncompatibleType() throws ArgumentException if an argument cannot be cast to a given type.
  • ThrowIfInvalidEnumValue() throws InvalidEnumArgumentException if an argument is not a constant in a given enumerated type.
  • ThrowIfNull() throws ArgumentNullException if an argument is a null reference (Nothing in Visual Basic).
  • ThrowIfOutOfRange() throws ArgumentOutOfRangeException if an argument is less than a given minimum or greater than a given maximum.
  • ThrowIfOutOfRangeExclusive() throws ArgumentOutOfRangeException if an argument is less than or equal to a given lower bound or greater than or equal to a given upper bound.
  • ThrowIfOutOfRangeIncludeMax() throws ArgumentOutOfRangeException if an argument is less than or equal to a given lower bound or greater than a given maximum.
  • ThrowIfOutOfRangeIncludeMin() throws ArgumentOutOfRangeException if an argument is less than a given minimum or greater than or equal to a given upper bound.

Why not simply Assert?

It’s good defensive programming practice to sprinkle Debug.Assert() liberally throughout your code in order to exterminate bugs before they crawl around and lay eggs. You might be wondering when you should opt to throw an exception instead of asserting a condition.

Here’s a rule of thumb:

  • Within private and internal members, call Debug.Assert().
  • Within protected, protected internal and public members, call Exceptions.ThrowIf… and/or throw custom exceptions.

My rationale is that code running in a different assembly should be given the opportunity to catch properly formatted exceptions. Assertions are for internal use only—housekeeping notes to yourself. Keep in mind that they don’t even get evaluated in release builds.

Testing the code

There’s no reason why you should trust that this code will do what it’s supposed to do. In fact, there’s little reason, apart from rigorous testing, why you should trust any source code in your projects, whether you wrote it or somebody else did. If the word “testing” sounds to you like somebody else’s job, then you’re passing the buck. And you’re also missing out on a way both to drastically improve the quality of your code and to reduce your stress about the quality of your code. Sounds impossible? Read about Alphonse (read the rest of the series, too) for an entertaining introduction to test-driven development. The XP gurus have informative things to say about TDD, too.

Whether you’re new to automated unit testing or are an experienced user of NUnit, MbUnit or other unit-testing frameworks, you should download and install a wonderful Visual Studio .NET add-in called TestDriven.NET. It provides a “friction-free” developer experience for running unit test cases from within the Visual Studio .NET 2003 IDE. You don’t need the other frameworks installed first; it comes complete. In fact, you might want to uninstall NUnit and MbUnit before installing TestDriven.NET.

Seriously: download it and install it right now. I’ll wait.

Back already? With TestDriven.NET installed, open the solution, Umbrae.Exceptions.Test.sln, in Visual Studio .NET 2003. Then right-click on ExceptionsTest.cs in the IDE and click the Run Test(s) menu item.

running automated unit test cases in Visual Studio .NET 2003 using TestDriven.NET

You should be able to see all the tests execute successfully in the IDE’s Output window:

------ Test started: Assembly: Umbrae.Exceptions.Test.dll ------


558 succeeded, 0 failed, 0 skipped, took 8.98 seconds.



---------------------- Done ----------------------

Feedback

I welcome your input on this, whether it be bug reports, flames, enhancement ideas, or unit tests I’ve neglected to write.

History

Wed 12/29/2004: Updated

  • Applied DebuggerHidden attribute to all Exceptions members that throw exceptions.
  • Updated HTML Help documentation to reflect member attributes.

Wed 12/22/2004: Updated

  • Changed out some thrown exceptions for Debug.Assert() calls in Exceptions.cs.
  • Updated XML documentation to cite fewer exceptions that may be thrown.
  • Updated examples to take into account assertions that may fail due to improper calls.
  • Commented out 66 unit tests that fail the new assertions.
  • Fixed a bug in ExceptionsTest.TemporaryTypeBuilder.CreateEnumTypeWithFlagsAttribute().
  • Shortened the method names.
  • Added four missing unit tests for ThrowIfDifferentRank().
  • Changed ThrowIfNull() to avoid unnecessarily composing the Message property.
  • Corrected typographical errors in the XML documentation.
  • Added remarks to the article on calling Debug.Assert() vs. throwing exceptions.
  • Made various changes to the text of the article.

Fri 12/10/2004: Originally submitted

License

This article, along with any associated source code and files, is licensed under The MIT License

About the Author

Nils Jonsson

Architect
NCite
United States United States

Member

Follow on Twitter Follow on Twitter
I’m part of a startup based in Houston, building products for law enforcement. I speak Ruby (since 2005), JavaScript (since 2005), and C# (since 2002).

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralFxCop warnings PinmemberJaap Faber1:49 3 Jul '07  
GeneralNice, but... PinsussSander Leer2:56 28 Dec '04  
GeneralRe: Nice, but... PinmemberNils Jonsson9:57 28 Dec '04  
GeneralRe: Nice, but... PinmemberSander Leer0:19 29 Dec '04  
GeneralRe: Nice, but... PinmemberNils Jonsson4:26 29 Dec '04  
GeneralRe: Nice, but... PinPopularmemberip25510:48 28 Dec '04  
GeneralRe: Nice, but... PinmemberNils Jonsson4:55 29 Dec '04  
GeneralSpeed/size analysis PinmemberEd Brey3:58 22 Dec '04  
One thing lacking from your article is the impact that using the Exceptions methods will have on size and speed of the code. A nice feature of the "if (...) RaiseError()" pattern, is that so long as the compiler is smart enough to not inline RaiseError, you get a fast check with minimial code size. (Of course, sometimes, RaiseError() is trivial, and won't even be a separate method.)
 
By bundling the check into the Exceptions method, the compiler would have to be smart enough inline only the check to get the optimal combination.
 
Another question: For the oh-so-common check for a null argument, why do you provide your own description, rather than let ArgumentNullException take care of that for you? It would seem that you're adding extra code only to undo the localization built into the .NET framework.
GeneralRe: Speed/size analysis PinmemberNils Jonsson5:36 22 Dec '04  
GeneralRe: Speed/size analysis PinmemberEd Brey5:51 22 Dec '04  
GeneralRe: Speed/size analysis PinmemberNils Jonsson6:54 22 Dec '04  
GeneralRe: Speed/size analysis Pinmemberpeterchen3:12 23 Dec '04  
QuestionWhy not assert? PinprotectorMarc Clifton11:24 20 Dec '04  
AnswerRe: Why not assert? PinmemberNils Jonsson11:13 21 Dec '04  
GeneralNice work. PinmemberAngelos Petropoulos0:51 20 Dec '04  
GeneralRe: Nice work. PinmemberNils Jonsson5:42 20 Dec '04  
GeneralRe: Nice work. PinmemberAngelos Petropoulos5:52 20 Dec '04  
GeneralLong names PinmemberFrank Hileman17:16 15 Dec '04  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120528.1 | Last Updated 31 Dec 2004
Article Copyright 2004 by Nils Jonsson
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid