Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

NumberFormatException

Thrown when a string cannot be converted to a number.

Available since: Java 1.0

Syntax

public class NumberFormatException extends IllegalArgumentException

Examples

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: ""
0

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.