繁体   English   中英

为什么我的try-catch在捕获错误时会打印出错误和catch块?

[英]Why does my try-catch when used to catch an error print out the error and my catch block?

我目前正在学习尝试捕获代码块,并且正在编写一段代码,该代码从用户处获取输入并检查其是否为整数。 我的代码是

int classSize = 0;
boolean error = false;
    do {
        try{
            System.out.println("Hello! Please enter how many Students you have in your class: ");
            classSize = in.nextInt();
            error = false;
        }
        catch(InputMismatchException e){
            System.out.println("Invalid input. please make sure you enter numbers ONLY! No symbols or letters.");
            classSize = in.nextInt();
            error = true;
        }
    }while(error);

当我尝试通过输入字母进行测试时,我同时收到错误消息和try阻止消息。

Hello! Please enter how many Students you have in your class: 
asdfsda

Invalid input. please make sure you enter numbers ONLY! No symbols or 
letters.

Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at ExcerciseOne.main(ExcerciseOne.java:65)

为什么显示catch块和错误消息? 我是否正确使用try-catch块?

您正在捕获在try子句中引发的异常,但是随后您再次从该catch内的扫描程序中读取并因此引发了另一个未捕获的异常。

classSize = in.nextInt();

在两个子句中都存在,两次都抛出异常,但是只有从try子句内部抛出时才被捕获。

catch块中的in.nextInt()调用读取try块中首次调用in.nextInt()留下的不良流。

您可以做的是在catch块中删除.nextInt()调用:

boolean hasError = true;
while (hasError) {
    try {
        System.out.println("Hello! Please enter how many Students you have in your class: ");
        classSize = in.nextInt();
        hasError = false;
    } catch (InputMismatchException e) {
        System.out.println("Invalid input. please make sure you enter numbers ONLY! No symbols or letters.");
        // variable has error remains true
    }
}

或更好:

由于InputMismatchExceptionRuntimeException的子类,因此可以通过if语句过滤掉引发此错误的错误类型。 由于只需要一个适当的整数作为输入,因此可以使用正则表达式来验证输入。

boolean hasError = true;
String integerRegex = "[\\d]+"; // it means 1-to-many digits
while (hasError) {
    System.out.println("Hello! Please enter how many Students you have in your class: ");
    String input = in.nextLine();
    if (input.matches(integerRegex)) {
        classSize = Integer.parseInt(input);
        hasError = false;
    } else {
        System.out.println("Invalid input. please make sure you enter numbers ONLY! No symbols or letters.");
        // variable hasError remains true
    }
}

Gendarme的答案很明确,我为您添加了一个正确的演示:

  public static void main(String[] args) {
      int studentsCount = 0;
      boolean hasError;
      do {
        try {
          System.out.println("Hello! Please enter how many Students you have in your class: ");
          Scanner in = new Scanner(System.in);
          studentsCount = in.nextInt();
          hasError = false;
        } catch (InputMismatchException e) {
          System.out.println("--> Invalid input. please make sure you enter numbers ONLY! No symbols or letters.");
          hasError = true;
        }
      } while (hasError);
      System.out.println("There are " + studentsCount + " students in your class.");
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM