When should I use a ThrowHelper method instead of throwing directly?

前端 未结 6 1737
傲寒
傲寒 2021-02-05 10:16

When is it appropriate to use a ThrowHelper method instead of throwing directly?

void MyMethod() {
    ...
    //throw new ArgumentNullException(\"param         


        
6条回答
  •  爱一瞬间的悲伤
    2021-02-05 10:50

    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, Funct errorHandler)
    {
      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.

提交回复
热议问题