Why does division by zero with floating point (or double precision) numbers not throw java.lang.ArithmeticException: / by zero in Java

In short, that's the way it's specified in the IEEE-754 standard, which is what Java's Floating-Point Operations are based on.

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.


It's that way because that's how IEEE 754 defined it.

Division by a floating point 0.0 yields NaN or +/-Inf, depending on whether the numerator is 0 or not.

Division by an integer 0 is not covered by IEEE 754, and generates an exception - there's no other way of indicating the error because an int can't represent NaN or Inf.

Generating an exception is similar to the (software) INT generated by a division by zero on x86 microprocessors.


To Infinity and Beyond

class DoubleDivision {

    public static void main(String[] args) {
        System.out.println(5.0/0.0);
    }
}

The above code, and the snippets you mentioned gives infinity.

Why Java uses Doubles to represent decimals. Binary cannot fully represent a number, it can only represent an approximation and therefore, neither can Java’s double.

Imagine a number incredibly close to zero. If you know calculus, imagine a limit at zero. The variable would be approaching zero to some imaginably tiny distance but never equal exactly. You can imagine that, right? Well, suppose that number is needs so much precision for Java to represent, it gives up and calls it 0.0 because it does not have a good alternative. That’s what is happening here. Any regular number divided by a super close number to zero is basically, infinity. Try it: 5 / (10^-100).

Also refer to section : Special Floating-Point Values at Math Errors for more info :)

Related question : why does 1/0 give error but 1.0/0/0 give inf

UPDATE: INT does not have an infinity and NaN value in set whereas float does have a infinity and NaN value. (According to IEEE 754 standards that java follows)