I was running a simple Calculator app to learn Java's exception handling. I've set two exceptions to be handled: InputMismatchException and ArithmeticException for division by zero.
ArithmeticException gets handled and the do-while loop continues. But after catching the InputMismatchException, the execution terminates rather than continuing the loop.
Code:
do {
result = 0;
System.out.println("Enter the expression to calculate: (eg: 4 + 5) \n");
try {
num1 = input.nextInt();
op = input.next().charAt(0);
num2 = input.nextInt();
result = a.Calc(num1, op, num2); //Calc function to calculate
System.out.println("= " + result);
} catch (InputMismatchException e) {
System.err.println("Please space out the expression");
} catch (ArithmeticException e) {
System.err.println("Cannot divide by zero");
}
System.out.println("Do you want to try again? (Y to retry)");
OP = input.next().charAt(0);
} while (OP == 'Y' || OP == 'y');
Output:
Enter the expression to calculate: (eg: 4 + 5)
4 / 0
Cannot divide by zero //Exception handled
Do you want to try again? (Y to retry)
Y //Do-while continues
Enter the question to calculate: (eg: 4 + 5)
4+5
Please space out the expression //Exception handled
Do you want to try again? (Y to retry) //Rest of the code is executed
//But the execution also terminates
Expected: Do-while to continue after InputMismatchException
Is this the correct way of doing this?