NumberFormatException in Java
Problem
A NumberFormatException is thrown when Integer.parseInt() (or similar parsing methods) receives a string that doesn't represent a valid number.
Parse a string that isn't a valid number into an int, and handle the resulting exception.
Java Program
public class NumberFormatExceptionDemo {
public static void main(String[] args) {
String input = "abc";
try {
int number = Integer.parseInt(input); // "abc" has no valid digit sequence
System.out.println("Parsed: " + number);
} catch (NumberFormatException e) {
System.out.println("Error: 'abc' is not a valid number");
}
}
}Output
Core Logic
Wrapping the parse attempt in try-catch lets an invalid numeric string be reported cleanly instead of crashing the program.
- 1
String input = "abc";holds text that doesn't represent any integer. - 2
Integer.parseInt(input)tries to convert it to anint, but there's no valid digit sequence to parse. - 3This throws a
NumberFormatExceptionat the moment of parsing. - 4The
catch (NumberFormatException e)block catches it and prints a message instead of letting the program crash.
"abc" throws immediately, caught and printed as "Error: 'abc' is not a valid number".Key Point: parseInt() has no partial-success mode — a string is either entirely a valid integer or the whole call fails, even if only one character is invalid.
Key Concepts
Approach 2: Java 8
import java.util.Optional;
public class NumberFormatExceptionOptional {
static Optional<Integer> tryParse(String s) {
try {
return Optional.of(Integer.parseInt(s));
} catch (NumberFormatException e) {
return Optional.empty(); // failure becomes an empty Optional instead of a thrown exception
}
}
public static void main(String[] args) {
String input = "abc";
String result = tryParse(input)
.map(n -> "Parsed: " + n)
.orElse("Error: 'abc' is not a valid number");
System.out.println(result);
}
}
Output
Core Logic
Optional can represent 'a parsed value, or nothing' directly — attempt the parse inside a helper that turns failure into an empty Optional, then let map()/orElse() handle both outcomes.
- 1A small helper
tryParse(String s)wrapsInteger.parseInt(s)in its own try-catch, returningOptional.of(result)on success orOptional.empty()on failure — this is what lets the failure be represented as a value instead of a thrown exception further down the pipeline. - 2
tryParse(input)returns an emptyOptionalfor"abc", since the parse inside it fails. - 3
.map(n -> "Parsed: " + n)only runs if theOptionalis present, formatting the successful result. - 4
.orElse("Error: 'abc' is not a valid number")supplies the fallback message if theOptionalwas empty.
input = "abc", tryParse() returns Optional.empty(), so .map() is skipped and .orElse(...) supplies the error message.Key Point: The try-catch doesn't disappear here — it just moves inside a small reusable helper, so the calling code reads as a value pipeline instead of a control-flow block.