Pattern to avoid nested try catch blocks?

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

    In Perl you can do foo() or bar(), which will execute bar() if foo() fails. In C# we don't see this "if fail, then" construct, but there's an operator that we can use for this purpose: the null-coalesce operator ??, which continues only if the first part is null.

    If you can change the signature of your calculations and if you either wrap their exceptions (as shown in previous posts) or rewrite them to return null instead, your code-chain becomes increasingly brief and still easy to read:

    double? val = Calc1() ?? Calc2() ?? Calc3() ?? Calc4();
    if(!val.HasValue) 
        throw new NoCalcsWorkedException();
    

    I used the following replacements for your functions, which results in the value 40.40 in val.

    static double? Calc1() { return null; /* failed */}
    static double? Calc2() { return null; /* failed */}
    static double? Calc3() { return null; /* failed */}
    static double? Calc4() { return 40.40; /* success! */}
    

    I realize that this solution won't always be applicable, but you posed a very interesting question and I believe, even though the thread is relatively old, that this is a pattern worth considering when you can make the amends.

提交回复
热议问题