gpt4 book ai didi

java - 即使捕获到异常,执行也会终止

转载 作者:行者123 更新时间:2023-12-02 00:37:37 25 4
gpt4 key购买 nike

我正在运行一个简单的计算器应用程序来学习 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

预期:在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/57962798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com