2017-07-21 55 views
-1

前几天我在这个网站上问了一个问题,但我认为那些分享他们的时间来帮助我的人(谢谢他们)并没有真正意识到我的观点。这里是链接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可以)。

(不是关键的例外,如内存不足或能力,是一个简单的异常,不会作任何的逻辑问题,所以是没有问题的忽视除外)

谢谢!

+0

更正它是否正确理解:如果有异常,你想退出循环? –

回答

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

作为一个方面说明,如果您发现自己想要这样做,那么您的设计模式有可能存在缺陷。

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 
    } 
} 

上面的代码将即使发生异常继续处理。

相关问题