2

Possible Duplicate:
Why doesn't Java throw an Exception when dividing by 0.0?

Why the following statement in Java will not report an ArithmeticException?

double d = 1.0/0;
Community
  • 1
  • 1
siva636
  • 16,109
  • 23
  • 97
  • 135
  • 3
    Because it's not an integer division. – Mysticial Jul 25 '12 at 04:14
  • Related: [Can I force java to throw an error when dividing by zero with floating point numbers?](http://stackoverflow.com/questions/576266/can-i-force-java-to-throw-an-error-when-dividing-by-zero-with-floating-point-num?rq=1) – Mysticial Jul 25 '12 at 04:16
  • @Mysticial Of course, but I want to know why only int divisions by zero results in exception!:-) – siva636 Jul 25 '12 at 04:17
  • 2
    That's probably a question for the designers of Java. But it's probably because integer divide-by-zero will trigger a hardware exception. But floating-point divide-by-zero simply returns an `INF` or `NaN`. – Mysticial Jul 25 '12 at 04:19
  • ... two values which cannot be expressed in an integer field. – Thilo Jul 25 '12 at 04:23

1 Answers1

9

In short: floating point numbers can represent infinity (or even operations that yield values which aren't numbers) so an operation that results in this (e.g. dividing by 0) is valid.

Expanding upon Mohammod Hossain's answer, as well as this question and its accepted answer, an ArithmeticException is thrown "Thrown when an exceptional arithmetic condition has occurred". For integers, dividing by 0 is such a case, but for floating point numbers (floats and doubles) there exist positive and negative representations.

As an example,

public class DivZeroFun {

    public static void main(String args[]) {

        double f = 5.0;
        System.out.println(f / 0);
        double f2 = -5.0;
        System.out.println(f2/0);
    }
}

This code will print "Infinity" and then "-Infinity" as its answers, because "Infinity" is actually an accepted value for floats and doubles that is encoded in Java.

Also, from this forum post:

Floating point representations usually include +inf, -inf and even "Not a Number". Integer representations don't. The behaviour you're seeing isn't unique to Java, most programming languages will do something similar, because that's what the floating point hardware (or low level library) is doing.

and again from the forum post:

Because the IEEE standard for floating point numbers used has defined values for positive and negative infinity, and the special "not a number" case. See the contants in java.lang.Float and java.lang.Double for details.

Community
  • 1
  • 1
blahman
  • 1,304
  • 1
  • 12
  • 18