简体   繁体   English

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

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

I am currently learning about try-catch blocks of code and I am writing a piece of code that takes an input from a user and checks if its a integer or not. 我目前正在学习尝试捕获代码块,并且正在编写一段代码,该代码从用户处获取输入并检查其是否为整数。 my code is 我的代码是

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);

When I try to test it by entering letters I get both the error message and the try block message. 当我尝试通过输入字母进行测试时,我同时收到错误消息和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)

Why is it showing the catch block and the error message? 为什么显示catch块和错误消息? Am I using the try-catch block properly? 我是否正确使用try-catch块?

You are catching the exception thrown in the try clause, but you are then reading from the scanner inside the catch again and thus throwing another exception, this time uncaught. 您正在捕获在try子句中引发的异常,但是随后您再次从该catch内的扫描程序中读取并因此引发了另一个未捕获的异常。

classSize = in.nextInt();

exists in both clauses, throwing an exception both times, but only gets caught when thrown from inside the try clause. 在两个子句中都存在,两次都抛出异常,但是只有从try子句内部抛出时才被捕获。

The in.nextInt() invocation inside the catch block reads the bad stream left behind by the first invocation of in.nextInt() in the try block. catch块中的in.nextInt()调用读取try块中首次调用in.nextInt()留下的不良流。

What you can do is to remove the .nextInt() calls in the catch block: 您可以做的是在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
    }
}

Or better: 或更好:

Since InputMismatchException is a subclass of RuntimeException , the kind of error that throws this error can be filtered out by if statements. 由于InputMismatchExceptionRuntimeException的子类,因此可以通过if语句过滤掉引发此错误的错误类型。 Since you only need a proper integer as an input, you can validate the input using a regular expression. 由于只需要一个适当的整数作为输入,因此可以使用正则表达式来验证输入。

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's answer is clear, and I add a correct demo for you: 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