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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With