InputMismatchException in Java
InputMismatchException is one of the most common exceptions in Java. The InputMissmatchException is an unchecked exception because it is a subclass of the java.lang.RuntimeException. The hierarchy for the java.util.InputMismatchException is as follows:
It provides all the methods which are provided by the java.lang.Throwable and the java.lang.Object classes because it is a subclass of both these classes.
Methods of java.lang.Throwable class
addSuppressed(), fillInStackTrace(), getCause(), getLocalizedMessage(), getMessage(), getStackTrace(), getSuppressed(), initCause(), printStackTrace(), printStackTrace(), printStackTrace(), setStackTrace(), and toString().
Methods of java.lang.Object class
clone(), equals(), finalize(), getClass(), hashCode(), notify(), notifyAll(), and wait(). To learn more about these methods, visit following:
https://tutoraspire.com/object-class
https://tutoraspire.com/post/java-throwable
The InputMismatchException class has the following two constructors:
InputMismatchException()
It is the default constructor which constructs InputMismatchException with null as its error message string.
InputMismatchException()
It is a parameterized constructor which constructs the InputMismatchException, saving a reference to the error message s for retrieval by the getMessage() method.
When does InputMismatchException occur?
This unchecked exception is thrown by the Scanner for indicating that the retrieved token does not match the pattern for the expected type or that the token is out of range for the expected type.
The java.util package provides a Scanner class to take input of primitive data types and strings from the user. It is the simplest way to read user input in java. The InputMismatchException occur when the user does not provide the proper type of input or input is out of range.
In simple words, we get the InputMismatchException when the input type is not correct. When the Scanner expects an integer as input, and we provide float value as input to the Scanner, it throws the InputMismatchException.
In the same way, when the Scanner expects an integer as input, and we provide Big Integer value as input to the Scanner, it will also throw the InputMismatchException.
InputMismatchExceptionExample1.java
Output:
InputMismatchExceptionExample2.java
Output:
How to avoid InputMismatchException
It is very simple to avoid InputmismatchException in Java. There is only one simple way to avoid this exception, i.e., providing valid input(either similar type or data should be expected data type range) to the Scanner.
In the above example, if we give five as input to the Scanner, the InputMismatchException will not occur.