DivisionByZero使用if else语句

Rat*_*tna 1 java exception-handling divide-by-zero

我有一个小问题,DivisionByZeroException如果我们可以处理if else块,有什么用处.我尝试使用谷歌搜索,但无法得到正确的答案.任何人都可以精心告诉我吗?提前致谢

Bud*_*dha 6

忘记DivisionByZeroException,使用if-else逻辑几乎可以避免所有异常.

Exceptions的重点是从一些意外情况中恢复并简化此恢复.如果有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
}
Run Code Online (Sandbox Code Playgroud)

如果你使用一些try 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
}
Run Code Online (Sandbox Code Playgroud)

一旦你像其他人一样获得了关于异常处理的一些好知识,第二种方法显然会更加清晰.在第二种方法中,代码流更容易明显.