What is the value of exception factories?

When looking at some code reflected from WCF libraries, I see a pattern used to create exceptions:

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

Zero arguments are the simplest example, and other types of exceptions are available through the static error class.

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

+6
exception factory
source share
3 answers

The biggest reason I found is to standardize how to handle exceptions and define them within a specific development team (or teams). Even Microsoft publishes that various types of exceptions are not standard between Exception, SystemException and ApplicationException. It is possible that the needs in this case may differ depending on the rules defining specific logical cases. It is also useful for eliminating common tasks (such as logging) from the everyday worries of the developer. All the developer has to do is use the appropriate exception in the factory, and the factory takes care of the rest.

+2
source share

I think the main reason is that .NET exception messages are localized. The actual message text must be extracted from the string resource. It is better to put such code in one place so that no one distorts the name of the string resource.

The idea of ​​using a factory so that the actual type of exception can be changed strikes me as less useful. This can break a lot of client code, which for some reason tries to catch this exception. When you submit code that throws a specific exception, you pretty much get stuck in it. Choose wisely :)

+5
source share

can a factory do extra work, like an exception log?

0
source share

All Articles