gpt4 book ai didi

java - 为什么这里被零除不触发异常?

转载 作者:太空狗 更新时间:2023-10-29 22:50:02 25 4
gpt4 key购买 nike

(这是 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.

如果将ad 的类型更改为int,则会出现异常。

关于java - 为什么这里被零除不触发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12130800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com