即使例外,继续尝试

时间:2017-07-21 05:32:38

标签: c# exception

前几天我在这个网站上提出了一个问题,但我认为那些分享时间帮助我的人(感谢他们)并没有真正意识到我的观点。这是链接Catch and Continue? C#

他们认为我想结束try-catch,并继续使用其余的代码。但我不

这是我的问题,但更多的改革:

我想获得try-catch,但我需要尝试到最后,即使它返回异常。像这样:

        // I thought a perfect example with math for this case.
        // It is possible to divide a number with negative and positive numbers
        // but it is not possible to divide a number by zero, So
        // 5/5= 1                  // ok
        // 5/4= 1.25               // ok
        // 5/3= 1.66666666667      // ok
        // 5/2= 2.5                // ok
        // 5/1= 5                  // ok
        // 5/0= Math Error // Oh, this is an error so I stop the try here.
        // 5/-1= -5                // foo
        // 5/-2= -2.5              // foo
        // 5/-3= -1.66666666667    // foo
        // 5/-4= -1.25             // foo
        // 5/-5= -1                // foo
        // foo = This is not a error, but I will not do it because the previous error

我需要的是“忽略”该异常并继续try-catch(通过忽略除零来划分所有正数和负数。)我该怎么做?

这只是我的问题的一个明显的例子,我知道有人会说将所有“数字”放在列表框中并删除我不想要的但是我的原始代码总是返回相同的异常 使用未定义的结果(两者都可以是x,可以是y。)

(不是一个关键的例外,例如内存或容量不足,是一个简单的例外,不会产生任何逻辑问题,因此忽略异常没有问题)

谢谢!

2 个答案:

答案 0 :(得分:2)

我认为这就是你想要的:

foreach(var x = 5; x > -5; x--)
{
    try
    {
        // Do the math here
    }
    catch(Exception)
    {
        // Log/Print exception, just don't throw one or the loop will exit
    }
}

即使发生异常,上述代码也会继续处理。

答案 1 :(得分:0)

try { operation1(); } catch { }
try { operation2(); } catch { }
try { operation3(); } catch { }
...

作为旁注,如果您发现自己想要这样做,那么您的设计模式可能存在缺陷。