(这是 Why is this exception is not printed? Why is it showing an error? 的后续问题)
在下面的代码中,为什么没有触发 ArithmeticException?
class Exp
{
public static void main(String args[])
{
float d,a=1;
try
{
d=0;
a=44/d; //no exception triggered here.. why?
System.out.print("It's not gonna print: a="+a);
}
catch(ArithmeticException e)
{
System.out.println("Print exception: "+e);
}
}
}
相反的输出是:
It's not gonna print: a=Infinity
会发生什么?
最佳答案
除以零会引发整数值异常,但不会引发浮点值异常。这是在 JLS #15.17.2 中定义的:
The result of a floating-point division is determined by the rules of IEEE 754 arithmetic:
[...]
- Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.
如果将a
和d
的类型更改为int
,则会出现异常。
关于java - 为什么这里被零除不触发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12130800/