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.
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? Am I using the try-catch block properly?