gpt4 book ai didi

java - 为什么除以 0 时 RuntimeException 不起作用?

转载 作者:搜寻专家 更新时间:2023-11-01 01:13:09 24 4
gpt4 key购买 nike

我想知道为什么这段代码执行时没有抛出 RuntimeException(恰好是 ArithmethicException ):

代码:

public class Proba {
public static void main(String[] args) {
Double d = new Double(5.0);
try {
d = d / 0;
} catch (Exception e) {
System.out.println("Error division by zero!");
}
System.out.println("d = " + d);
}
}

输出:

d = Infinity

我想知道这是怎么可能的。

我的java版本是:

C:\Documents and Settings\Admintemp>java -version
java version "1.7.0"
Java(TM) SE Runtime Environment (build 1.7.0-b147)
Java HotSpot(TM) Client VM (build 21.0-b17, mixed mode, sharing)
  • 为什么这种行为在 Java 中是可能的?

最佳答案

这是可能的,因为 Java 遵循浮点除法的 IEEE 标准。

的确,整数除以 0 会抛出 ArithmeticException,但 float 除以 0 会产生一个特殊的浮点值 Infinity

详细说明,the JLS, Section 15.17.2说:

[I]f the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

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.

这就提出了一个问题,“为什么 IEEE 声明它应该是Infinity 而不是某种错误?” 这是 IEEE'sexplanation :

Why doesn't division by zero (or overflow, or underflow) stop the program or trigger an error? Why does a standard on numbers include "not-a-number" (NaN)? The 754 model encourages robust programs. It is intended not only for numerical analysts but also for spreadsheet users, database systems, or even coffee pots. The propagation rules for NaNs and infinities allow inconsequential exceptions to vanish. Similarly, gradual underflow maintains error properties over a precision's range.

When exceptional situations need attention, they can be examined immediately via traps or at a convenient time via status flags. Traps can be used to stop a program, but unrecoverable situations are extremely rare. Simply stopping a program is not an option for embedded systems or network agents. More often, traps log diagnostic information or substitute valid results.

Flags offer both predictable control flow and speed. Their use requires the programmer be aware of exceptional conditions, but flag stickiness allows programmers to delay handling exceptional conditions until necessary.

关于java - 为什么除以 0 时 RuntimeException 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19253020/

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