NumberFormatException
JavaERRORCommonParsing

Invalid number format string

Quick Answer

Wrap parseInt in try-catch or validate the string with a regex before parsing.

What this means

Thrown when a string cannot be parsed into a numeric type — e.g., Integer.parseInt on a non-numeric string.

Why it happens
  1. 1Parsing user input that contains letters or spaces
  2. 2Empty string passed to parseInt

Fix

Wrap in try-catch

Wrap in try-catch
try {
    int n = Integer.parseInt(input);
} catch (NumberFormatException e) {
    System.err.println("Not a number: " + input);
}

Why this works

Catching NumberFormatException lets you provide a fallback or user-facing error.

Code examples
Triggerjava
Integer.parseInt("abc"); // NumberFormatException
Safe parse helperjava
OptionalInt parse(String s) {
    try { return OptionalInt.of(Integer.parseInt(s)); }
    catch (NumberFormatException e) { return OptionalInt.empty(); }
}
Validate firstjava
if (s != null && s.matches("-?\d+")) {
    int n = Integer.parseInt(s);
}
Sources
Official documentation ↗

Java SE Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Java errors