Pattern to avoid nested try catch blocks?

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

    You could flatten out the nesting by putting it into a method like this:

    private double calcStuff()
    {
      try { return calc1(); }
      catch (Calc1Exception e1)
      {
        // Continue on to the code below
      }
    
      try { return calc2(); }
      catch (Calc2Exception e1)
      {
        // Continue on to the code below
      }
    
      try { return calc3(); }
      catch (Calc3Exception e1)
      {
        // Continue on to the code below
      }
    
      throw new NoCalcsWorkedException();
    }
    

    But I suspect the real design problem is the existence of three different methods that do essentially the same thing (from the caller's perspective) but throw different, unrelated exceptions.

    This is assuming the three exceptions are unrelated. If they all have a common base class, it'd be better to use a loop with a single catch block, as Ani suggested.

提交回复
热议问题