4

I must have done something stupid here. But I can't seem to figure out why this simple code doesn't work. The InputMismatchException works, but the ArithmeticException never get caught.

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);
    }
}
Michael
  • 7,348
  • 10
  • 49
  • 86

3 Answers3

13

If you expect ArithmeticException to be thrown when dividing by 0.0, it won't. Division of a double by 0 returns either Double.POSITIVE_INFINITY (dividing a positive double by 0.0), Double.NEGATIVE_INFINITY (dividing a negative double by 0.0) or Double.NaN (dividing 0.0 by 0.0).

Division of an int by 0 will give you this exception.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

It is because you are not throwing exception, most possible what happening is you are trying divide number by 0. As you are using float, this operations is allowed. As result you will get Infinity or NaN

if you change your input to integer, then you will have your exception

user902383
  • 8,420
  • 8
  • 43
  • 63
1

ArithmaticException is not thrown for float division by zero. It would work with integer division. See this answer for more detail.

Community
  • 1
  • 1