Why doesn't a RuntimeException work when you divide by 0?

I am interested to know why this piece of code is executed without Throwing RuntimeException(exactly ArithmethicException ):

Code:

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

Output:

d = Infinity

I want to know how this is possible.

My java version:

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)
  • Why is this behavior possible in Java?
+4
source share
1 answer

This is possible because Java follows the IEEE standard for floating point division.

It is true that integer division by 0 will generate ArithmeticException, but division by floating point by 0 gives a special floating point value for Infinity.

To develop, JLS, section 15.17.2 , says:

[I] f 0, ArithmeticException.

IEEE 754:

()

. .

: " IEEE , Infinity - ? " IEEE :

( ) ? "-" (NaN)? 754 . , , . NaNs . , .

, . , . . .

, . , , .

+13

All Articles