CKTIS / Java
NumberFormatException — failed text-to-number conversion
NumberFormatException signals that text cannot be converted to the requested numeric type. With Integer.parseInt, the cause can be either invalid notation or a value outside the int range.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
try {
int value = Integer.parseInt(text);
} catch (NumberFormatException e) {
// Handle invalid numeric input.
}NumberFormatException, in java.lang, indicates a failed conversion from text to a numeric type. It extends IllegalArgumentException and is unchecked: the compiler does not require catching it or declaring it in throws.
For Integer.parseInt(text), the default radix is 10. An initial + or - is permitted, but whitespace, empty text, and characters other than valid digits cause failure. Even valid numeric notation, such as "2147483648", causes NumberFormatException because the value exceeds the int range. For this method, null also causes this exception; do not generalize that behavior to every conversion method.
Catch NumberFormatException near the input-processing boundary and handle rejection explicitly. Do not silently substitute zero. Remove surrounding whitespace only if the input rules permit it; doing so will not fix an out-of-range value.
The example separates a successful conversion from two failures: an invalid character and an out-of-range value. It prints its own message rather than relying on the exception message text.
Examples
public class Main {
public static void main(String[] args) {
String[] inputs = {"42", "12x", "2147483648"};
for (String text : inputs) {
try {
int value = Integer.parseInt(text);
System.out.println(text + " -> " + value);
} catch (NumberFormatException e) {
System.out.println(text + " -> invalid int");
}
}
}
}Result
42 -> 42 12x -> invalid int 2147483648 -> invalid int
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.