Java InputMismatchException
Example
Read a number from text that is not a number, and catch the exception:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner("Hello");
try {
int myNum = myObj.nextInt();
System.out.println(myNum);
} catch (InputMismatchException e) {
System.out.println("Error: please enter a whole number.");
}
}
}
Definition and Usage
An InputMismatchException happens when a Scanner reads a value of the wrong type, for example when nextInt() finds text instead of a whole number.
It usually happens when the user types something unexpected. In the example, the Scanner reads from the text "Hello" instead of the keyboard, so the result is always the same.
Tip: Use hasNextInt() to check if the next value is a whole number, before you read it.
Related Pages
Java Exceptions (try...catch) Tutorial
❮ Errors & Exceptions