java - 算术异常 :/by zero only works on integers in Java

标签 java exception casting floating-point integer

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

我的代码:

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

输出:

2147483647
Infinity
Exception in thread "main" java.lang.ArithmeticException: / by zero

每次我将一个数字除以一个整数(byte、short、int、long)时,它都会抛出 ArithmeticException,而用实数(float、double)时则不会出现这种情况。为什么?

最佳答案

来自 JLS §15.17.2 :

  • Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.

除了:

if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

关于java - 算术异常 :/by zero only works on integers in Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24878815/

相关文章:

java - Android Retrofit 2 发布请求响应以及响应类名称

java - Java多态性中的困惑

java - 有没有办法让 "folded code"在 Android Studio 中保持折叠状态?

Java catch异常设计与性能

java - 如何创建带有复选框的 JSF 表?

java - Spring Data JPA 错误处理的最佳实践是什么

c# - 为什么使用 double.Parse 然后转换为 float ?

java - 返回类型值的通用方法

c++ - 在 C 中将 double 转换为整数时处理溢出

python - Python 中的通用异常处理 "Right Way"