p>The InputMismatchException
is a runtime exception in Java that is thrown by a Scanner
object to indicate that a retrieved token does not match the pattern for the expected type, or that the token is out of range for the expected type.
Since InputMismatchException
is an unchecked exception, it does not need to be declared in the throws
clause of a method or constructor.
 
What Causes InputMismatchException
The InputMismatchException
generally occurs when working with Java programs that prompt users for input using the Scanner
class. The exception can occur when the input is invalid for the expected type. The input either does not match the pattern for the expected type, or is out of range.
For example, if a program expects an Integer
value for an input but the user enters a String
value instead, an InputMismatchException
is thrown.
 
InputMismatchException Example
Here is an example of an InputMismatchException
thrown when a String
is entered as input to a Scanner
that expects an integer:
import java.util.Scanner;
public class InputMismatchExceptionExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter an integer: ");
int integer = scanner.nextInt();
scanner.close();
System.out.println("You entered: " + integer);
}
}
In the above code, the user is prompted for an integer as input. The Scanner.nextInt()
method is used to retrieve the value, which expects an integer as input. If the user enters a String
value instead of an integer, an InputMismatchException
is thrown:
Enter an integer:
String
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 InputMismatchExceptionExample.main(InputMismatchExceptionExample.java:8)
 
How to Fix InputMismatchException
To avoid the InputMismatchException
, it should be ensured that the input for a Scanner
object is of the correct type and is valid for the expected type. If the exception is thrown, the format of the input data should be checked and fixed for the application to execute successfully.
In the above example, if an integer is entered as input to the Scanner
object, the InputMismatchException
does not occur and the program executes successfully:
Enter an integer:
5
You entered: 5
 
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!