2013-12-19 43 views
1

我有一個小問題,如果我們可以處理if else塊,那麼DivisionByZeroException的用法是什麼。我試着用谷歌搜索,但不能得到正確的答案。任何人都可以詳細地告訴我嗎?提前致謝DivisionByZero通過使用if else語句

+0

不是一個標準問題 –

+2

有人會問這個問題嗎? –

+1

在java中它是[ArithmeticException](http://docs.oracle.com/javase/7/docs/api/java/lang/ArithmeticException.html) –

回答

6

忘掉DivisionByZeroException,幾乎所有的異常都可以通過使用if-else邏輯來避免。

例外情況的要點是從某種意外情況中恢復並簡化此恢復。如果有10個地方可能會在您的代碼中出現異常,則必須確保您已包含所有if-else條件。異常處理簡化了這一點。你不必在每一個可能的地方進行驗證,只要嘗試一下,就會發現一旦發生異常情況。

這也提供了簡單的方法來爲不同的例外提供不同的恢復機制。

if(check for first type of exception) 
{ 
    do first task 
} 
else 
{ 
    return one type of error 
} 
do some intermediary task 
if(check for first type of exception && check for second type of exception) 
{ 
    do second task 
} 
else 
{ 
    if(exception is of one type) 
     return one type of error 
    if(exception is of second type) 
     return another type of error 
} 

上面的代碼可以更清楚,如果你使用一些嘗試catch塊如下...

try{ 
    do first task 
    do some intermediary task 
    do second task 
} 
catch(first type of exception) 
{ 
    return one type of error 
} 
catch(second type of exception) 
{ 
    return second type of error 
} 
catch(another type of exception developer may have forgotten) 
{ 
    return a generic error 
} 

第二種方法顯然會更加清楚,一旦你獲得了異常處理的一些好的知識就像其他人一樣。在第二種方法中,代碼流更容易明顯。

+1

另外還有一件東西是佛陀說的。假設你正在使用第三方api(JXL/JNA等)..你不知道如果你傳遞錯誤的參數值會發生什麼..被調用的函數可能會說「throws someException」(錯誤的編程實踐順便說一句)...在這種情況下,你不知道你會得到什麼異常..如果你不知道你會得到什麼異常,你如何使用if-else來防止它? ..使用異常,你可以通過一般化的方式來捕捉它,並將其作爲「JXLException/JNAException ..」來處理。 – TheLostMind

+0

是的...好點。你並不總是知道除了什麼。 – Buddha