【发布时间】:2012-12-17 18:15:52
【问题描述】:
为什么这段代码不抛出ArithmeticException?看看:
public class NewClass {
public static void main(String[] args) {
// TODO code application logic here
double tab[] = {1.2, 3.4, 0.0, 5.6};
try {
for (int i = 0; i < tab.length; i++) {
tab[i] = 1.0 / tab[i];
}
} catch (ArithmeticException ae) {
System.out.println("ArithmeticException occured!");
}
}
}
我不知道!
【问题讨论】:
-
那么如何更改我的代码以获得 ArithmeticException? (我不想将数组的类型更改为 int)?
-
if (tab[i] == 0) throw new ArithmeticException();. -
凯蒂,你想多了。 :) assylias 解决方案很好。如果出于某种原因,您不想抛出 ArithmeticException,只需抛出您想要的异常即可。
-
使用
==检查浮点值可能容易出错。您应该始终检查足够小的数字,以排除舍入错误。