我正在运行一个简单的计算器应用程序来学习 Java 的异常处理。我已经设置了两个要处理的异常:用于除零的 InputMismatchException 和 ArithmeticException。
ArithmeticException 得到处理,do-while 循环继续。但是在捕捉到 InputMismatchException 之后,执行终止而不是继续循环。
代码:
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');
输出:
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
预期:Do-while 在 InputMismatchException 之后继续
这是正确的做法吗?
最佳答案
InputMismatchException
是由调用 nextInt()
引起的,因为下一个标记是 4+5
。
失败的调用未消耗 token 。
这意味着 OP = input.next().charAt(0)
设置 OP = '4'
,如果你 调试代码。参见 What is a debugger and how can it help me diagnose problems?和 How to debug small programs .
您需要丢弃失败的 token ,例如通过在 catch
子句中调用 nextLine()
:
} catch (InputMismatchException e) {
System.err.println("Please space out the expression");
input.nextLine(); // Discard input(s)
} ...
关于java - 即使捕获到异常,执行也会终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57434945/