Pattern to avoid nested try catch blocks?

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

    Just to offer an "outside the box" alternative, how about a recursive function...

    //Calling Code
    double result = DoCalc();
    
    double DoCalc(int c = 1)
    {
       try{
          switch(c){
             case 1: return Calc1();
             case 2: return Calc2();
             case 3: return Calc3();
             default: return CalcDefault();  //default should not be one of the Calcs - infinite loop
          }
       }
       catch{
          return DoCalc(++c);
       }
    }
    

    NOTE: I am by no means saying that this is the best way to get the job done, just a different way

提交回复
热议问题