views:

40

answers:

3

In looking at some code reflected from the WCF libraries, I'm seeing a pattern used to create exceptions:

if(argument == null)
{
    throw Error.ArgumentNull("argument");
}

Null arguments being the simplest example, with other types of exceptions available through the static error class.

What is the value of this factory pattern? Why not use the new operator and simply call the ArgumentNullException constructor?

A: 

The factory could perform additional work, like log the exception maybe?

Sam Holder
It could only log the creation of the exception. No stack trace or any really useful information at that stage.
Programming Hero
+2  A: 

The biggest reason I've found is to standardize how exceptions are handled and defined within the framework of a particular development team (or teams). Even Microsoft publishes that the various exception types are not specifically standard between Exception, SystemException and ApplicationException. It could be that the needs of the exception may be different depending on the rules governing specific logic cases. It is also useful for removing common tasks (such as logging) from the developer's everyday concerns. All the developer has to do is use the appropriate exception in the factory and the factory takes care of the rest.

Joel Etherton
Got any examples of the kind of standardization you're referring to?
Programming Hero
@Programming Hero - I was referring to internal standards. For instance, within our development team here at work, we (the leads) got together shortly after being assigned to our first project and hashed out the basics of what we wanted: naming standards, logging, exception handling, event handling, n-tier architecture, etc. We didn't create a factory ourselves, but we did specify in our standards docs to use System.Exception instead of ApplicationException and the standards for when exceptions should be logged, caught, handled or ignored.
Joel Etherton
+2  A: 

I think the primary reason is that .NET exception messages are localized. The actual message text needs to be retrieved from a string resource. Better to put that kind of code in one place so that nobody will fumble the string resource name.

The idea of using a factory so that the actual exception type can be tweaked strikes me as less than useful. Doing so can break a lot of client code that, for whatever reason, tries to catch that exception. Once you ship code that throws a specific exception, you're pretty much stuck with it. Choose wisely :)

Hans Passant