Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the value of Exception factories?

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?

like image 886
Paul Turner Avatar asked Aug 13 '10 12:08

Paul Turner


2 Answers

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 :)

like image 174
Hans Passant Avatar answered Nov 15 '22 13:11

Hans Passant


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.

like image 35
Joel Etherton Avatar answered Nov 15 '22 12:11

Joel Etherton