Division by zero in double = result Infinity

2

I was learning about handling errors in the Java language and I tested the example code of the class in question. In a test I added (double) to the final operation to leave the result more accurate and I noticed that after that, when I tried to divide any number "x" by "0", instead of the "ArithmeticException" error I would receive a " Infinity "as a result.

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

Follow 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);
    
asked by anonymous 17.02.2017 / 19:16

1 answer

2

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

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

    
18.02.2017 / 03:28