Java - Cannot grab arithmetic exception when dividing by zero

I must have done something stupid here. But I can not understand why this simple code does not work. An InputMismatchException is thrown, but an ArithmeticException is never thrown.

import java.util.InputMismatchException;
import java.util.Scanner;
public class SubChap02_DivisionByZero {
    public static double quotient(double num, double denum) throws ArithmeticException {
        return num / denum;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double num, denum, result;
        boolean continueLoop = true;
        do {
            try {
                System.out.printf("Please enter the numerator: ");
                num = scanner.nextFloat();
                System.out.printf("Please enter the denumerator: ");
                denum = scanner.nextFloat();
                result = quotient(num, denum);
                continueLoop = false;
                System.out.printf("THIS: %.2f/%.2f is %.2f\n", num, denum, result);    
                scanner.close();
          } catch (ArithmeticException arithmeticException) {
              System.err.printf("Exception : %s\n", arithmeticException);
              scanner.nextLine();
              System.out.println("You can try again!");
          } catch (InputMismatchException inputMismatchException) {
              System.err.printf("Exception : %s\n", inputMismatchException);
              scanner.nextLine();
              System.out.println("You can try again!");
          }
      } while (continueLoop == true);
    }
}
+4
source share
3 answers

If you expect what ArithmeticExceptionwill be selected when dividing by 0.0, this will not happen. Dividing double by 0 returns either Double.POSITIVE_INFINITY(dividing the positive double by 0.0), Double.NEGATIVE_INFINITY(dividing the negative double by 0.0) or Double.NaN(dividing 0.0 by 0.0).

Dividing int by 0 will give you this exception.

+12
source

, , , , 0. float, . Infinity NaN

,

+1

ArithmaticException float- . . . .

+1

All Articles