Pattern to avoid nested try catch blocks?

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

    Given that the calculation methods have the same parameterless signature, you can register them in a list, and iterate through that list and execute the methods. Probably it would be even better for you to use Func meaning "a function that returns a result of type double".

    using System;
    using System.Collections.Generic;
    
    namespace ConsoleApplication1
    {
      class CalculationException : Exception { }
      class Program
      {
        static double Calc1() { throw new CalculationException(); }
        static double Calc2() { throw new CalculationException(); }
        static double Calc3() { return 42.0; }
    
        static void Main(string[] args)
        {
          var methods = new List> {
            new Func(Calc1),
            new Func(Calc2),
            new Func(Calc3)
        };
    
        double? result = null;
        foreach (var method in methods)
        {
          try {
            result = method();
            break;
          }
          catch (CalculationException ex) {
            // handle exception
          }
         }
         Console.WriteLine(result.Value);
       }
    }
    

提交回复
热议问题