ArithmeticException in Java

In Java (Number / 0) throws an arithmetic exception while (Number / 0.0) = Infinity. Why is this happening?

+6
java math floating-point
source share
3 answers

Since IEEE-754 floating point numbers have a representation for infinity, while integers do not.

In other words, each bit pattern in int represents a normal integer; floating point values ​​are more complex with +/- infinity, non-number (NaN) values, normalized values, subnormal values, etc.

+13
source share

From here

The IEEE floating point standard, supported by almost all modern processors, indicates that every floating point arithmetic operation, including division by zero, has a well-defined result. The standard supports signed zero, as well as infinity and NaN (rather than a number). There are two zeros, +0 (positive zero) and -0 (negative zero), and this eliminates any ambiguity in the division. In arithmetic, IEEE 754 Γ· + 0 is positive infinity when a is positive, negative infinity when a is negative, and NaN when a = Β± 0. Signs of infinity change when divided by -0 instead.

Integer division by zero is usually handled differently than floating point, because there is no integer representation for the result. Some processors throw an exception when an attempt is made to divide an integer by zero, although others will simply continue and generate the wrong result for division. The result depends on how the division is performed, and can be either zero or sometimes the largest possible integer.

+3
source share

You can also check out JLS which says:

15.17.2 Department Operator
On the other hand, if the value of the divisor in integer division is 0, an ArithmeticException is thrown.

The result of floating point division is determined by the IEEE Arithmetic specification: If the result is not NaN, the sign of the result is positive if both operands have the same sign, negative if the operands have different signs.
Dividing a nonzero final value by zero leads to marked infinity. The sign is determined by the above rule.

0
source share

All Articles