图案以避免嵌套的try catch块? [英] Pattern to avoid nested try catch blocks?

查看:104
本文介绍了图案以避免嵌套的try catch块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个情况我有执行计算的三个(或更多)的方式,每一个都可以失败,一个例外。为了尝试每一次计算,直到我们找到一个成功,我一直在做以下内容:

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 find one that succeeds, I have been doing the following:

double val;

try { val = calc1(); }
catch (Calc1Exception e1)
{ 
    try { val = calc2(); }
    catch (Calc2Exception e2)
    {
        try { val = calc3(); }
        catch (Calc3Exception e3)
        {
            throw new NoCalcsWorkedException();
        }
    }
}



有没有公认的格局其中实现这一目标的一个更好的方式?当然,我可以包中失败则返回空一个辅助方法每次计算,然后只用 ?? 运营商,但有没有这样做更普遍的一种方式(即无需写我想用每一种方法)一个辅助方法?我想过写使用泛型它包装在一个try / catch任何给定的方法,失败时返回null一个静态方法,但我不知道我怎么会去这一点。任何想法?

Is there any accepted pattern which achieves this in a nicer way? Of course I could wrap each calculation in a helper method which returns null on failure, and then just use the ?? operator, but is there a way of doing this more generally (i.e. without having to write a helper method for each method I want to use)? I've thought about writing a static method using generics which wraps any given method in a try/catch and returns null on failure, but I'm not sure how I would go about this. Any ideas?

推荐答案

尽量不要使用控制流或平常的情况例外。

As far as possible, don't use exceptions for control flow or unexceptional circumstances.

但直接回答你的问题(假设所有的异常类型相同):

But to answer your question directly (assuming all the exception-types are the same):

Func<double>[] calcs = { calc1, calc2, calc3 };

foreach(var calc in calcs)
{
   try { return calc(); }
   catch (CalcException){  }
} 

throw new NoCalcsWorkedException();

这篇关于图案以避免嵌套的try catch块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆