算术异常:/ by零仅适用于Java中的整数

Him*_*wal 3 java floating-point integer casting exception

为什么在将数字除以零时有如此不同的答案:

我的代码:

class Test {
  public static void main(String[] args){

    int a = (int)(3/0.0F);
    System.out.println(a);

    System.out.println(3/0.0F);

    System.out.println(3/0);
  }
}
Run Code Online (Sandbox Code Playgroud)

输出:

2147483647
Infinity
Exception in thread "main" java.lang.ArithmeticException: / by zero
Run Code Online (Sandbox Code Playgroud)

每当我将一个数字除以一个整数(byte,short,int,long)时,它就会抛出ArithmeticException,这与使用实数(float,double)完成时不同.为什么?

alf*_*sin 5

来自JLS§15.17.2:

  • 将零非零有限值除以零会产生有符号无穷大.该标志由上述规则确定.

除了:

如果整数除法中除数的值为0,则抛出ArithmeticException.

  • @mikez显而易见的答案是"IEEE 754",缺乏一种实现整数的方法,因为没有整体的"NaN". (4认同)