NumberFormatException
Thrown when a string cannot be converted to a number.
Available since: Java 1.0
Syntax
public class NumberFormatException extends IllegalArgumentExceptionExamples
Parsing input safely:
int parseOrDefault(String s, int fallback) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
IO.println(e.getMessage());
return fallback;
}
}
void main() {
IO.println(parseOrDefault("42", 0));
IO.println(parseOrDefault("4 2", 0));
IO.println(parseOrDefault("", 0));
}Output:
42
For input string: "4 2"
0
For input string: ""
0Notes
It is thrown by Integer.parseInt(), Double.parseDouble() and similar methods for spaces, letters, an empty string or a value outside the type's range. Surrounding spaces can be removed with strip() before parsing. It is a subclass of IllegalArgumentException.
See also
- IllegalArgumentException — Signals that a method received an invalid argument.
- ArithmeticException — Thrown on an invalid arithmetic operation, such as integer division by zero.
In the tutorial
- try, catch and finally — Handling exceptions in Java — the try and catch blocks, several catch blocks, multi-catch, finally and throwing exceptions with throw.