2014-06-27 27 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; 

捕获异常只应赶上意外