Pattern to avoid nested try catch blocks?

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

    It sounds like your calculations have more valid information to return than just the calculation itself. Perhaps it would make more sense for them to do their own exception handling and return a "results" class that contains error information, value information, etc. Think like the AsyncResult class does following the async pattern. You can then evaluate the real result of the calculation. You can rationalize this by thinking in terms that if a calculation fails, that's just as informational as if it passes. Therefore, an exception is a piece of information, not an "error."

    internal class SomeCalculationResult 
    { 
         internal double? Result { get; private set; } 
         internal Exception Exception { get; private set; }
    }
    
    ...
    
    SomeCalculationResult calcResult = Calc1();
    if (!calcResult.Result.HasValue) calcResult = Calc2();
    if (!calcResult.Result.HasValue) calcResult = Calc3();
    if (!calcResult.Result.HasValue) throw new NoCalcsWorkedException();
    
    // do work with calcResult.Result.Value
    
    ...
    

    Of course, I'm wondering more about the overall architecture that you're using to get these calculations done.

提交回复
热议问题