2017-07-21 54 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 
    } 
} 

上面的代碼將即使發生異常繼續處理。

相關問題