2014-06-27 29 views
-1

我有一些功能,即計算出的數字,我捕捉異常:的try-catch處理程序,並DivideByZeroException

try{ 
.... 
return mainCount /count; 
} 
catch (DivideByZeroException ex) 
     { 

      return 0; 
     } 
     catch (Exception ex) 
     { 

      return 0; 
     } 

那麼,是抓吧?或者可能是程序崩潰?

謝謝!

+0

它不會崩潰,但你爲什麼不試一試? – Adil

回答

3

決不Exception(基類)不扔:它的意思是 「無論發生了剛剛返回零」。這不是在情況下,期望的行爲,比如,內部.NET錯誤或RAM腐敗......

try { 
    ... 
    return mainCount/count; 
    } 
    catch (DivideByZeroException) { // <- You don't need instance ("ex") here 
    // quite OK: return 0 when count == 0 
    return 0; 
    } 

更好的做法,但是,僅僅是測試如果count == 0

return count == 0 ? 0 : mainCount/count; 

典型模式與Exception趕上

try { 
    ... 
    } 
    catch (Exception e) { 
    // Whatever had happend, write error to log 
    SaveToLog(e, ...); 
    // And throw the exception again 
    throw; // <- not "throw e;"! 
    } 
2

你不應該使用例外來規定你的程序的流程,你可以很容易地看到這裏可能發生什麼錯誤,所以我建議如下

if(count == 0) 
    return 0; 
return mainCount/count; 

捕獲異常只應趕上意外