InputMismatchException in Java
beginner· Exceptions · Error Handling
Problem
An InputMismatchException is thrown when a Scanner method like nextInt() is called but the next token in its input isn't actually formatted as that type.
Use Scanner.nextInt() to read a token that isn't a valid integer, and handle the resulting exception.
Input
new Scanner("abc").nextInt()
Output
Error: Expected an integer but the input wasn't one
Java Program
Java
import java.util.InputMismatchException;
import java.util.Scanner;
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner("abc");
try {
int number = scanner.nextInt(); // "abc" isn't formatted as an integer
System.out.println("Number: " + number);
} catch (InputMismatchException e) {
System.out.println("Error: Expected an integer but the input wasn't one");
}
}
}Output
Error: Expected an integer but the input wasn't one
Core Logic
Wrapping the risky nextInt() call in try-catch lets a badly-formatted token be caught and reported instead of crashing the program.
How It Works
- 1
new Scanner("abc")builds aScannerreading from the fixed string"abc"instead of real console input, keeping the example self-contained and repeatable. - 2
scanner.nextInt()tries to read the next token and interpret it as anint. - 3Since
"abc"isn't formatted as an integer, this throws anInputMismatchExceptionrather than returning a value. - 4The
catch (InputMismatchException e)block catches it and prints a message instead of letting the program crash.
Calling
nextInt() on a scanner reading "abc" throws immediately, caught and printed as "Error: Expected an integer but the input wasn't one".💡
Key Point: Scanner can read from any source of text, not just the console — building one directly from a String, like here, is a common way to test input-parsing logic without needing real keyboard input.
Key Concepts
try / catchScannerInputMismatchException