Pattern to avoid nested try catch blocks?

后端 未结 16 551
無奈伤痛
無奈伤痛 2020-12-12 12:53

Consider a situation where I have three (or more) ways of performing a calculation, each of which can fail with an exception. In order to attempt each calculation until we f

16条回答
  •  天命终不由人
    2020-12-12 13:24

    As far as possible, don't use exceptions for control flow or unexceptional circumstances.

    But to answer your question directly (assuming all the exception-types are the same):

    Func[] calcs = { calc1, calc2, calc3 };
    
    foreach(var calc in calcs)
    {
       try { return calc(); }
       catch (CalcException){  }
    } 
    
    throw new NoCalcsWorkedException();
    

提交回复
热议问题