- What is InputMisMatchException in Java how do we handle it?
- Example
- Runtime exception
- Handling input mismatch exception
- How to Fix the Input Mismatch Exception in Java?
- What Causes InputMismatchException
- InputMismatchException Example
- How to Fix InputMismatchException
- Track, Analyze and Manage Errors With Rollbar
- InputMismatchException in Java with Examples
- When does InputMismatchException occur?
- InputMismatchException is an Unchecked Exception
- Example of InputMismatchException
- How to avoid InputMismatchException
- Java exception input mismatch exception
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Java exception input mismatch exception
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
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.
How to Fix the Input Mismatch Exception in Java?
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!
InputMismatchException in Java with Examples
In this tutorial, we will discuss the InputMismatchException in java. Also, we will answer whether InputMismatchException is a checked exception or unchecked exception. Before diving deep into the topic let us first understand when does InputMismatchException occur.
When does InputMismatchException occur?
InputMismatchException is thrown by a Scanner to indicate that the token retrieved 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. It is the simplest way to read user input in java. If the user does not provide the proper type of input or input is out of range, then InputMismatchException happens.
InputMismatchException is an Unchecked Exception
The java.util package provides InputMismatchException class that inherits NoSuchElementException class. NoSuchElementException inherits RuntimeException. So, InputMismatchException is a runtime exception. Hence, it is an unchecked exception.
This class has two constructors that are listed below.
public InputMismatchException() It is not accepting any exception message parameter. By default, it gives null value as message. public InputMismatchException(String s) This constructor receives exception message as parameter.
Example of InputMismatchException
The InputMismatchException exception is produced only when the input type is not proper, for example, if java application expects long datatype as input but the user gives the float value as input it should generate InputMismatchException exception. Please find below the code example.
import java.util.InputMismatchException; import java.util.Scanner; public class JavaHungry public static void main(String[] args) Scanner scanner = new Scanner(System.in); try System.out.println("Enter Integer Value: "); Integer inputInt = scanner.nextInt(); // input : "1.1" System.out.println(inputInt); > catch (InputMismatchException ex) System.out.println("We have given input as float expecting integer "+ ex); > > >
Output:
Enter Integer Value: 1.1
We have given input as float expecting integer java.util.InputMismatchException
In the above example, if the application is looking for integer value but we have provided a float value.
Case 2: Again if we provide an input that is not within integer range
import java.util.InputMismatchException; import java.util.Scanner; public class JavaHungry public static void main(String[] args) Scanner scanner = new Scanner(System.in); try System.out.println("Enter Integer Value: "); Integer inputInt = scanner.nextInt(); // input : "12222222222222222" System.out.println(inputInt); > catch (InputMismatchException ex) System.out.println("input is not with in integer range "+ ex); > > >
Output:
Enter Integer Value: 12222222222222222
input is not with in integer range java.util.InputMismatchException
These examples are true for every datatype. If input data does not comply below two conditions, then InputMismatchException will generate.
1. Input data type not match.
2. Input data is not in the range of expected datatype.
In the above examples, we are exiting from the code when the exception generates.
How to avoid InputMismatchException
When we provide a valid input that will comply with the conditions described in the above section. Only correct input can avoid this kind of exception.
That’s all for today, please mention in comments in case you have any questions related to InputMismatchException in java.
About The Author
Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry
Java exception input mismatch exception
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Java exception input mismatch exception
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter