Click here to Skip to main content
Email Password   helpLost your password?

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:

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:

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

Wed 12/22/2004: Updated

Fri 12/10/2004: Originally submitted

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralFxCop warnings
Jaap Faber
2:49 3 Jul '07  
Hi,
Thanks for this. Like other writers in the messages, I too am used to Delphi Asserts. And it was the first thing in C# I missed. The code presented here solves part of the problem. And a extra debug hidden tag helps a lot. But there is one problem for me: I like to use FxCop to check for (some) errors. One of them is the checking of parameters. But with the code presented here, FxCop fails to understand that parameter checking is just wat we are doing! Is there a way to combine the use FxCop and the code presented here?
Regards, Jaap.

GeneralNice, but...
Sander Leer
3:56 28 Dec '04  
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...
Nils Jonsson
10:57 28 Dec '04  

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&shy;If&shy;Out&shy;Of&shy;Range&shy;Include&shy;Max&shy;Core() and Exceptions.Throw&shy;If&shy;Out&shy;Of&shy;Range&shy;Include&shy;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&shy;Box.OnPaint(): a null argument throws a Null&shy;Reference&shy;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...
Sander Leer
1:19 29 Dec '04  
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

GeneralRe: Nice, but...
Nils Jonsson
5:26 29 Dec '04  
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­&shy;If&shy;­Out&shy;­Of&shy;­Range&shy;­Include&shy;­Max&shy;­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&shy;Null&shy;Exception in Check&shy;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&shy;Event&shy;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...
ip255
11:48 28 Dec '04  
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.
GeneralRe: Nice, but...
Nils Jonsson
5:55 29 Dec '04  
This is exactly what we needed. I just tried it and it works like a charm. I’ll upload the change.

Many thanks.

-- /\/. _/.
GeneralSpeed/size analysis
Ed Brey
4: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
Nils Jonsson
6:36 22 Dec '04  
Ed, thanks for the feedback.

You’re right that refactoring check-and-throw logic into a separate method may compromise compiler optimization. The question is, Does it matter? I generally avoid helping compiler optimization at the expense of programmer convenience unless I have hard data from a profiler to prove it’s a problem. My guess is that the impact will vary from app to app. Only a code profiler run against your app will prove that you need to back out the refactorings I’ve suggested here.

You’re also right about ArgumentNullException—I am needlessly building the message. I’ll change this.

-- /\/. _/.
GeneralRe: Speed/size analysis
Ed Brey
6:51 22 Dec '04  
I agree that developers' brains have lots of things better to concentrate on than compilation details. That's all the more reason for one, centralized analysis at the library level. Just as a developer appreciates knowing that the library is rung out with umpteen unit tests, it's a big time saver to see look up the typical time/space cost of using the library, and from that make the call: (1) performance hit acceptable: use without remorse, or (2) too much, use the standard logic. The one thing no one wants to have to do is start using the library and then try to discover via profiling whether its resulting in a ten percent slow-down due to extra calls or cache misses caused by a larger native image.
GeneralRe: Speed/size analysis
Nils Jonsson
7:54 22 Dec '04  
You may have a point, but I stand by my assertion that these things vary from app to app—there is no “typical.” Thus the need for profiling and perf counters.

For example, if your project is a class library, like a set of WinForms controls, you’re likely going to have many public members and therefore will make a lot of calls to Exceptions.ThrowIf&hellip;. A monolithic WinForms app won’t have the need for as many calls to Exceptions.ThrowIf&hellip; because most of the code is internal to the assembly.

I don’t know that you can generalize about image size—it all depends on how often you call these methods.

Check out the free Process Explorer for powerful .NET app runtime analysis and nprof for profiling.

-- /\/. _/.
GeneralRe: Speed/size analysis
peterchen
4:12 23 Dec '04  
Ed Brey wrote:
he one thing no one wants to have to do is start using the library and then try to discover via profiling whether its resulting in a ten percent slow-down due to extra calls or cache misses caused by a larger native image

This is, with todays Hardware/Compiler - Technology, very unlikely to happen. Most 10% slowdowns are not noticed by the user, and those which are can be nailed down to 1or a few places - and in these places, the "callee verifies" approach is likely to be a problem anyway.




we are here to help each other get through this thing, whatever it is Vonnegut jr.
boost your code || Fold With Us! || sighist | doxygen

GeneralWhy not assert?
Marc Clifton
12:24 20 Dec '04  
Since this seems to be for method argument validation rather than user input validation, why not use Debug.Assert? If the argument is bad, then it's a bug, and it should be caught during testing.

Marc

MyXaml
Advanced Unit Testing

GeneralRe: Why not assert?
Nils Jonsson
12:13 21 Dec '04  
Excellent question.

I’ll update the article to address it, but here’s my take on this:


  • Use Debug.Assert() within private and internal members

  • Use throw within protected, protected internal and public members



My rationale is as follows. If the code can be called by code running in a different assembly, then such an assembly may not belong to you—it may be another developer calling your code. That developer will appreciate your throwing a properly formatted exception that he can catch instead of having a failed assertion foul up the works of his app that references your assembly. (Never mind that he gave you a bad argument—he still deserves an exception.)

If the code can only be called by code running in the same assembly, then it’s your source and you might like the convenience of a failed assertion.

I check arguments and throw exceptions instead of Assert()ing even in a situation like this:

using System;
using System.Drawing;
using System.Windows.Forms;


namespace Umbrae.Windows.Forms
{
public class MyForm : Form
{
public MyForm() : base()
{
}


protected override void OnPaint(PaintEventArgs e)
{
Exceptions.ThrowIfArgumentNull(e, "e");

// TODO: Implement OnPaint().
}
}
}


The reason is that I don’t know who might subclass MyForm at some point and pass a bad PaintEventArgs argument to my implementation of OnPaint(). They should get an ArgumentNullException, not a NullReferenceException or some other inappropriate weirdness.

Just my opinion, though.

-- /\/. _/.
GeneralNice work.
Angelos Petropoulos
1:51 20 Dec '04  
The whole project is tested thoroughly and is well documented. Very nice work.

Would it be OK if I changed the name of the class from Exception to something else and used it in my projects?

Angelos Petropoulos
GeneralRe: Nice work.
Nils Jonsson
6:42 20 Dec '04  
Thanks.

Sure—you can adapt it however you need to. I expected developers to want to change the namespace to match their own root namespace.

It would be great if you kept my name in the credits, though.

I’m not using VS 2005, but C#’s new partial keyword would come in real handy here. You could easily add your own application-specific argument exceptions in a separate .cs file and still have them show up as members of the same class.

-- /\/. _/.
GeneralRe: Nice work.
Angelos Petropoulos
6:52 20 Dec '04  
Thank you. I will most certainly be keeping your name in the credits, including a link to this article.

Angelos Petropoulos
GeneralLong names
Frank Hileman
18:16 15 Dec '04  
We created a similar class. You don't really need the "ThrowIf" prefix everywhere, if the class name fulfills that purpose. For example, if the class is named check, Check.ArgumentNull(...). Just a little more compact.Smile

Nice article.

check out VG.net: www.vgdotnet.com
An animated vector graphics system integrated in VS.net


Last Updated 31 Dec 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010