Java除以零不会抛出ArithmeticException - 为什么?

Kat*_*tie 39 java arithmeticexception

为什么这段代码不会抛出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!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我不知道!

Pet*_*rey 68

IEEE 754定义1.0 / 0.0为Infinity,-1.0 / 0.0as -Infinity和0.0 / 0.0NaN.

BTW浮点还拥有-0.01.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");
Run Code Online (Sandbox Code Playgroud)

  • BTW`0.0 == -0.0`所以你不必检查两个值. (3认同)
  • 要检查所有特殊值(即 NaN、Infinity、-Infinity),请使用 `if (!Double.isFinite(d))` (3认同)
  • @Katie你可以在`tab [i] = 1.0/tab [i];之前检查`if(tab [i] == 0.0){throw new ArithmeticException();}` (2认同)
  • 建议的编辑队列已满,因此这里有一个未损坏的 IEEE 754 链接 https://ieeexplore.ieee.org/document/30711 (2认同)

Waq*_*yas 20

为什么你不能自己检查它,如果你想要的话就抛出异常.

    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!");
    }
Run Code Online (Sandbox Code Playgroud)

  • 您还需要检查Double.isNaN(). (8认同)
  • 这并不能回答问题。 (4认同)

gd1*_*gd1 17

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

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


cod*_*Man 11

0.0是双字面值,这不被视为绝对零!没有例外,因为它被认为是足够大的双变量来保存代表无穷大的值!

  • 不,0.0 确实是 0,并且 IEEE 浮点规范将结果定义为一个特殊值“正无穷大”,而不仅仅是一个非常大的值。 (2认同)

小智 6

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

如果除以0.0,结果将为INFINITY.


Ram*_*pta 6

除以零时

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

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

    安慰: Infinity

  2. 如果将 int 除以 0,则 JVM 将抛出算术异常

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

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