Click here to Skip to main content
Click here to Skip to main content

I take exception to that argument!

By , 30 Dec 2004
 

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
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.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralNice, but...sussSander Leer28 Dec '04 - 2:56 
I've used the same kind of library the last few years for my own projects, but I couldn't find a way to throw the exception from the correct source-code.
 
Currently an exception is thrown from the library methods instead of the method that is using this library. This is confusing for the programmer who's using your methods. Things get even worse when using the overloaded methods because they increase the length of the stack-trace.
 
Anyone knows how to throw an exception from a specific source location (in Delphi you can use raise object at address to raise an exception from an earlier point in the stack than the one where the error actually occurred).
GeneralRe: Nice, but...memberNils Jonsson28 Dec '04 - 9:57 

I get your point but I don’t see how it makes much practical difference. To illustrate, if a class library uses Exceptions.cs to raise an argument exception, here’s what I see in my Call Stack window when an exception is thrown to my WinForms client:

 
  • Umbrae.Class­Library1.dll!Umbrae.Exceptions.Throw­If­Out­Of­Range­Include­Max­Core(System.IComparable value = {0}, string name = "positive­Argument", System.Value­Type lower­Bound = {0}, System.Value­Type max­Value = {2147483647}) Line 2922
  • Umbrae.Class­Library1.dll!Umbrae.Exceptions.Throw­If­Out­Of­Range­Include­Max(int value = 0, string name = "positive­Argument", int lower­Bound = 0, int max­Value = 2147483647) Line 2373
  • Umbrae.Class­Library1.dll!Umbrae.Class­Library1.Class1.My­Method(int positive­Argument = 0) Line 21
  • Umbrae.Windows­Application1.exe!Umbrae.Windows­Application1.Form1.button1_Click(System.Object sender = {Text="button1"}, System.Event­Args e = {System.Event­Args}) Line 90
  • [<Non-user Code>]
  • Umbrae.Windows­Application1.exe!Umbrae.Windows­Application1.Form1.Main() Line 84
 

I don’t know what’s confusing or bothersome about that. Exceptions.Throw­If­Out­Of­Range­Include­Max­Core() and Exceptions.Throw­If­Out­Of­Range­Include­Max() seem to be self-explanatory as internal methods for checking argument validity. And if Umbrae.Class­Library.dll is referenced as a compiled assembly without source code, it won’t show up in the Call Stack anyway unless the developer chooses the “Show Non-user Code” preference.

 

Besides, this kind of somewhat extraneous information already shows up in the stack trace if you pass a bad argument, say, to System.Windows.Forms.Check­Box.OnPaint(): a null argument throws a Null­Reference­Exception with a stack trace that starts out:

 
  • System.Windows.Forms.dll!System.Windows.Forms.Check­Box.Paint­Up(System.Windows.Forms.Paint­Event­Args e = <undefined value>, System.Windows.Forms.Check­State state = Unchecked) + 0x51 bytes
  • System.Windows.Forms.dll!System.Windows.Forms.Check­Box.Paint­Over(System.Windows.Forms.Paint­Event­Args e = <undefined value>, System.Windows.Forms.Check­State state = Unchecked) + 0x48 bytes
  • System.Windows.Forms.dll!System.Windows.Forms.Check­Box.Paint­Standard(System.Windows.Forms.Paint­Event­Args pevent = <undefined value> ) + 0x33 bytes
  • System.Windows.Forms.dll!System.Windows.Forms.Check­Box.Paint­Control(System.Windows.Forms.Paint­Event­Args pevent = <undefined value> ) + 0x32 bytes
  • System.Windows.Forms.dll!System.Windows.Forms.Check­Box.OnPaint(System.Windows.Forms.Paint­Event­Args pevent = <undefined value> ) + 0x35 bytes
  • Umbrae.Windows­Application1.exe!Umbrae.Windows­Application1.My­Check­Box.On­Click(System.Event­Args e = {System.Event­Args}) Line 21
  • [...]
  • Umbrae.Windows­Application1.exe!Umbrae.Windows­Application1.Form1.Main() Line 94
 

Note that I had to choose the “Show Non-user Code” preference to get the WinForms methods to show up in the Call Stack.

 

I say stop worrying about confusing developers in this way.


 
-- /\/. _/.
GeneralRe: Nice, but...memberSander Leer29 Dec '04 - 0:19 
It makes a lot of difference when there's an error in Class1.MyMethod and the stack trace show there's an exception thrown from Exceptions.Throw­If­Out­Of­Range­Include­Max­Core. To an average programmer this is confusing; because they are not used to look halfway down the stack trace to see were the error originated.
 
Second, when referencing (as you suggest in your article) the Exception framework, the debugger breaks into the source-code of Exceptions.Throw­If­Out­Of­Range­Include­Max­Core, which might be confusing too.
 
Your second example using a CheckBox doesn't make sense. In none of the methods on the stack trace there are argument validation checks. So what you see in this example is a plain old bug (hence, it is throwing Null­Reference­Exception instead of a ArgumentNullException). Happily CheckBox.PaintUp is on the top of the stack trace, because that's where I must fix this bug! (Microsoft should have added validation checks in PaintUp).
 

Don’t get me wrong: I like your code and I hope every developer starts using it. Then at least a lot of pre-conditions are caught and overall quality of source-code will improve. I just whished I had some more control adding debugging code using "throwing exceptions at addresses", "method in-lining" or "preprocessing my source code".
 
Cheers, Sander Leer
 
PS. For me the "show non-user code" preference is always on because the bug is always in somebody’s else his code Poke tongue | ;-P

GeneralRe: Nice, but...memberNils Jonsson29 Dec '04 - 4:26 
Sander Leer wrote:
Second, when referencing (as you suggest in your article) the Exception framework, the debugger breaks into the source-code of Exceptions.Throw­­If­­Out­­Of­­Range­­Include­­Max­­Core, which might be confusing too.
 
This article does not provide an exception framework, only a C# source file to be included in your projects. The article states, “This utility class is designed to be included in your C# projects, not referenced as a compiled assembly.”
 
I used the CheckBox example to illustrate that it’s typical, when using referenced assemblies such as WinForms, to have exceptions thrown from private methods. You’re right that MS probably should be throwing an Argument­Null­Exception in Check­Box.OnPaint(), but it makes no difference to you because the only bug you can fix is in your own code that passed in the null Paint­Event­Args. Generally I find “Show Non-user Code” to be useful only to tell me under-the-covers stuff that’s nice to know about the BCL since I don’t have the source and can only fix my “user code” anyway.
 
I’ll agree with you that it would be cool to have Delphi’s simple way of tweaking the stack frame.
 
Thanks for the thoughtful feedback.
 
-- /\/. _/.
GeneralRe: Nice, but...memberip25528 Dec '04 - 10:48 
If you just want to see a shorter call stack when you break into the debugger, you could tag all the methods in the Exceptions class with the [DebuggerHidden] attribute. It won't help if you retrieve the stack trace programmatically, but if you're using Visual Studio, it will make the debugger break at the line where the problem actually occurred (the point where you're calling Exceptions.ThrowIfNull or whatever), instead of breaking inside ThrowIfNull.

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

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