When is it appropriate to use a ThrowHelper method instead of throwing directly?
void MyMethod() {
...
//throw new ArgumentNullException(\"param
One advantage not yet mentioned to using either a throw-helper or exception-factory method is the possibility of passing a delegate for such a purpose. When using a throw-helper delegate, one gains the possibility of not throwing (which would in some cases be a good thing; in other cases, a bad thing). For example:
string TryGetEntry(string key, FuncterrorHandler) { if (disposed) return errorHandler(problemCause.ObjectDisposed); else if (...entry_doesnt_exist...) return errorHandler(problemCause.ObjectNotFound); else return ...entry...; } string GetEntry(string key) { return TryGetEntry(key, ThrowExceptionOnError); } bool TryGetEntry(string key, ref result) { bool ok; string result; result = TryGetEntry(key, (problemCause theProblem) => {ok=false; return (string)null;}); return ok; }
Using this approach, one may easily use one routine with a variety of error-handling strategies. One could eliminate the need for a closure by having the TryGetEntry method accept a generic type parameter along with a 'ref' parameter of that type and a delegate that accepts such a 'ref' parameter; the example is simpler, though, just using a closure.