Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Cannot Catch ArithmeticException when dividing by zero [duplicate]

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);
    }
}
like image 548
Adhiputra Perkasa Avatar asked Dec 09 '22 04:12

Adhiputra Perkasa


1 Answers

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.

like image 186
Eran Avatar answered Jan 10 '23 21:01

Eran