56

Why doesn't this code throw an ArithmeticException? Take a look:

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!");
        }
    }
}

I have no idea!

4

8 回答 8

92

IEEE 754定义1.0 / 0.0为 Infinity 和-1.0 / 0.0-Infinity 以及0.0 / 0.0NaN。

顺便说一句,浮点值也有-0.0,所以1.0/ -0.0也是-Infinity

整数算术没有这些值,而是抛出异常。

要检查可能产生非有限数的所有可能值(例如 NaN、0.0、-0.0),您可以执行以下操作。

if (Math.abs(tab[i] = 1 / tab[i]) < Double.POSITIVE_INFINITY)
   throw new ArithmeticException("Not finite");
于 2013-01-03T11:27:35.677 回答
28

如果这是您想要的,为什么您不能自己检查并抛出异常。

    try {
        for (int i = 0; i < tab.length; i++) {
            tab[i] = 1.0 / tab[i];

            if (tab[i] == Double.POSITIVE_INFINITY ||
                    tab[i] == Double.NEGATIVE_INFINITY)
                throw new ArithmeticException();
        }
    } catch (ArithmeticException ae) {
        System.out.println("ArithmeticException occured!");
    }
于 2013-01-03T11:36:09.743 回答
25

那是因为您正在处理浮点数。除以零返回Infinity,类似于NaN(不是数字)。

如果你想防止这种情况发生,你必须tab[i]在使用它之前进行测试。然后你可以抛出你自己的异常,如果你真的需要它。

于 2013-01-03T11:25:57.840 回答
12

0.0 是一个双字面值,这不被视为绝对零!也不例外,因为它被认为是双变量大到足以容纳表示接近无穷大的值!

于 2013-01-03T11:25:57.460 回答
10

如果除以浮点零,Java 不会抛出异常。只有当您除以整数零而不是双零时,它才会检测到运行时错误。

如果除以 0.0,结果将是 INFINITY。

于 2015-11-19T08:34:39.803 回答
7

除以零时

  1. 如果将 double 除以 0,JVM 将显示Infinity

    public static void main(String [] args){ double a=10.00; System.out.println(a/0); }
    

    安慰: Infinity

  2. 如果将 int 除以 0,则 JVM 将抛出Arithmetic Exception

    public static void main(String [] args){
        int a=10;
        System.out.println(a/0);
    }
    

    安慰:Exception in thread "main" java.lang.ArithmeticException: / by zero

于 2017-10-01T10:55:49.760 回答
3

有一个技巧,算术异常仅在您使用整数时发生,并且仅在 / 或 % 操作期间发生。

如果算术运算中有任何浮点数,则内部所有整数都将转换为浮点数。这可以帮助您轻松记住事情。

于 2018-11-15T18:19:59.890 回答
0

这是浮点运算的行为是规范的。规范摘录,第 15.17.2 节。除法运算符 /

非零有限值除以零导致有符号无穷大。符号由上述规则确定。

于 2019-11-25T06:34:46.393 回答