Pattern to avoid nested try catch blocks?

后端 未结 16 541
無奈伤痛
無奈伤痛 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:15

    Try not to control logic based on exceptions; note also that exceptions should be thrown only in exceptional cases. Calculations in most cases should not throw exceptions unless they access external resources or parse strings or something. Anyway in the worst case follow the TryMethod style (like TryParse()) to encapsulate exception logic and make your control flow maintainable and clean:

    bool TryCalculate(out double paramOut)
    {
      try
      {
        // do some calculations
        return true;
      }
      catch(Exception e)
      { 
         // do some handling
        return false;
      }
    
    }
    
    double calcOutput;
    if(!TryCalc1(inputParam, out calcOutput))
      TryCalc2(inputParam, out calcOutput);
    

    Another variation utilizing the Try pattern and combining list of methods instead of nested if:

    internal delegate bool TryCalculation(out double output);
    
    TryCalculation[] tryCalcs = { calc1, calc2, calc3 };
    
    double calcOutput;
    foreach (var tryCalc in tryCalcs.Where(tryCalc => tryCalc(out calcOutput)))
      break;
    

    and if the foreach is a little complicated you can make it plain:

            foreach (var tryCalc in tryCalcs)
            {
                if (tryCalc(out calcOutput)) break;
            }
    

提交回复
热议问题