Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArithmeticException thrown in Java

In Java, (Number/0) throws an ArithmeticException while (Number/0.0) = Infinity. Why does this happen?

like image 232
Mohit Avatar asked Jan 27 '10 12:01

Mohit


2 Answers

Because IEEE-754 floating point numbers have a representation for infinity, whereas integers don't.

In other words, every bit pattern in int represents a normal integer; floating point values are rather more complicated with +/- infinity, "not a number" (NaN) values, normalized values, subnormal values etc.

like image 74
Jon Skeet Avatar answered Oct 26 '22 08:10

Jon Skeet


From here

The IEEE floating-point standard, supported by almost all modern processors, specifies 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 (not a number). There are two zeroes, +0 (positive zero) and −0 (negative zero) and this removes any ambiguity when dividing. In IEEE 754 arithmetic, a ÷ +0 is positive infinity when a is positive, negative infinity when a is negative, and NaN when a = ±0. The infinity signs change when dividing by −0 instead.

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

like image 29
stacker Avatar answered Oct 26 '22 07:10

stacker