HandleException() signature

Topics: Exception Handling Application Block
Jul 20, 2007 at 4:10 AM
I didn't know whether this should be filed as an issue or a discussion, so I'll take a guess and mention it here.

The signature for HandleException() in the Exception Handling Block looks like:

public static bool HandleException(Exception exceptionToHandle, string policyName);

I suggest that the first parameter, exceptionToHandle be a ref parameter, unless there is indeed a case where passing null has meaning for this method.

Since this method is intended for use in a catch block, and I don't think a catch block can ever receive an uninitialized parameter, HandleException() probably shouldn't accept null as part of its contract. I haven't looked at the source, but assuming there is some exceptionToHandle != null guard, it too could be removed. The method signature would also more clearly convey (enforce) it's expectation for use with previously existing exception instances, as it is when called in the typical fashion in a catch block.

I'm an (ex?) C++ guy, and what brought this to mind is it seems analogous to the general best practice of catching exceptions by reference in that language. C# exception handling seems to natively mirror this practice by forcing exceptions to be reference types, while also preventing a catch block from receiving an unitialized reference.

Jul 20, 2007 at 3:08 PM

Keep in mind that while ref will force the parameter to be a variable that has been initialized, null is as good an initialization value as any. The method doesn't accept nulls as part of the contract, that's the reason for the guard.

Here's a short repro.

class Program
static void Main(string[] args)
object local = null;
Foo(ref local);

static void Foo(ref object parameter)
Debug.Assert(parameter != null);

Jul 24, 2007 at 5:25 PM
Excellent point Fernando.

I guess this is one case where C# hasn't improved on C++. It is interesting that one can assign null to a variable and it still qualifies as "initialized" for ref's purposes. This is a violation of the spirit of a reference, IMHO.

Oh well. The "check for null" boilerplate guards I see over and over in C# code is sad. I hope the designers recognize this and provide native language support for expressing this sort of contract requirement directly in the method signature (a la C++ style references).