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

标签 java

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

相关文章:

java - 从 Java 对象生成正确的 JSON - Jackson

java - 如何从整个内存中删除()和setUp()?

java - 如何使列表像队列一样执行并仍然返回值?

java - 如何设置JSlider在窗口中的位置?

java - 我的工具栏太高,因此看起来很难看,并且下面的屏幕被裁剪,我该如何修复它?

java - 检查管理员登录( HashMap )

java - 如何在 Jquery TagIt 中不包含特殊字符和数字

java - 使用 Java (Spring) 从数据库安排任务的最佳方式

java - 我如何在另一个类中使用数组纹理?

java - ByteBuffer - CompareTo 方法可能会出现分歧