You are catching InputMismatchException
but typing a letter instead of a number raise a NumberFormatException
.
You can use a generic catch
exception:
try {
}
catch(Exception e){ //<-- Generic exception
}
Or use multiple catch block:
try {
}
catch(InputMismatchException | NumberFormatException e ){ //<-- Multiple exceptions
}
Updated to explain why InputMismatchException
doesn’t work:
That’s true that this exception
check if the value read by the Scanner
match with the type you want. But in your code you use .nextLine()
method which expect a ‘new line’.
These new line is a String
and can be compound by letters, numbers… that’s why the exception is not raised. The type match with the scanner
.
If you want to check using only this exception
you can use this:
try {
scanner.nextInt();
} catch (InputMismatchException e) {
}
Using this, if you type a String
the exception will be raised because your Scanner
expects an int
.
2
solved NumberFormatException – try/catch for parse value