What is InputMisMatchException in Java how do we handle it?


From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions.

To read various datatypes from the source using the nextXXX() methods provided by this class namely, nextInt(), nextShort(), nextFloat(), nextLong(), nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(), nextFloat(), next().

Whenever you take inputs from the user using a Scanner class. If the inputs passed doesn’t match the method or an InputMisMatchException is thrown. For example, if you reading an integer data using the nextInt() method and the value passed in a String then, an exception occurs.

Example

import java.util.Scanner;
public class StudentData{
   int age;
   String name;
   public StudentData(String name, int age){
      this.age = age;
      this.name = name;
   }
   public void display() {
      System.out.println("Name of the student is: "+name);
      System.out.println("Age of the student is: "+age);
   }
   public static void main (String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.next();
      System.out.println("Enter your age: ");
      int age = sc.nextInt();
      StudentData obj = new StudentData(name, age);
      obj.display();
   }
}

Runtime exception

Enter your name:
Krishna
Enter your age:
twenty
Exception in thread "main" java.util.InputMismatchException
   at java.util.Scanner.throwFor(Unknown Source)
   at java.util.Scanner.next(Unknown Source)
   at java.util.Scanner.nextInt(Unknown Source)
   at java.util.Scanner.nextInt(Unknown Source)
   at july_set3.StudentData.main(StudentData.java:20)

Handling input mismatch exception

The only way to handle this exception is to make sure that you enter proper values while passing inputs. It is suggested to specify required values with complete details while reading data from user using scanner class.

Updated on: 07-Aug-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements