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?
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.