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 开发者_Python百科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?
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 :)
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.
The factory could perform additional work, like log the exception maybe?
精彩评论