Division by zero into double = Infinity result

Asked

Viewed 996 times

2

I was learning about error handling in the Java language and did tests with the sample code of the class in question. In a test I added (double) in the final operation to make the result more accurate and noticed that after that, when I tried to divide any number "x" by "0", instead of the error "Arithmeticexception" I received an "Infinity" as a result.

Why does this happen? And why this only occurs for operations with floating point numbers (since, with the operation on integers, the error normally occurred)?

Follows the code:

Scanner s = new Scanner(System.in);
boolean continua = true;

        do {
            try {
                System.out.print("Numerador: ");
                int a = s.nextInt();
                System.out.print("Denominador: ");
                int b = s.nextInt();

                System.out.println("O resultado da divisão foi: " + (double) a / b);

                s.close();
                continua = false;
            }
            catch (InputMismatchException e1) {
                System.err.println("Informe um número inteiro");
                s.nextLine();
            }
            catch (ArithmeticException e2) {
                System.err.println("Denominador deve ser diferente de zero");
                s.nextLine();
            }
        } while (continua);
  • 1

    http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.2

  • 2

    No integer or real number can be divided by zero. This is not from programming logic, but from mathematics.

  • 1

    http://stackoverflow.com/a/2381633/6809703

1 answer

2


The float and double types implement the IEEE 754 standard, which defines that a division by zero should return a special value "infinite".

Launching Exception, as in int type, would violate this pattern.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.