1

I am trying to run below program and expecting Arithmetic Exception because we are dividing double value by zero but getting Infinity as output.

This is below program. But if we are using int instead of double then getting Arithmetic Exception

public static void main(String z[]) {
    Double a = 10.0;
    Double b = 0.0;
    System.out.println(a/b);
}

Output: Infinity

public static void main(String z[]) {
    int a = 10;
    int b = 0;
    System.out.println(a/b);
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at (Test.java:94)

Can someone please explain why we are getting Infinity for Double value?

Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94

2 Answers2

1

Refer to the language spec:

if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

...

The result of a floating-point division is determined by the rules of IEEE 754 arithmetic:

  • Division of a nonzero finite value by a zero results in a signed infinity.

Floating point division can have a non-exceptional result because there is a special value to indicate it. There is no such special value for integer division, so returning any integer result would be incorrect; the only option is to throw an exception.

Community
  • 1
  • 1
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

In IEEE 754 floating point operations, dividing a value by 0 (resp. 0.0) is well-defined and results in an "infinite" value, either positive or negative, depending on the involved values.

In integer domain, no such thing is defined and thus you get an ArithmeticException.

glglgl
  • 89,107
  • 13
  • 149
  • 217