Course contentsShow
← Java
Lesson 800 of 2,87019. Exception Hierarchy and Custom ExceptionsFree lesson

NumberFormatException: String to Number Conversion Failures

Understand when parsing strings to numbers fails and how to handle NumberFormatException.

NumberFormatException: String to Number Conversion Failures

What you'll learn: How to handle errors when converting string representations of numbers into actual numeric types.

What Is NumberFormatException?

NumberFormatException is a runtime exception thrown when you attempt to convert a string to a number, but the string doesn't contain a valid numeric format. It's an unchecked exception that extends IllegalArgumentException, signaling that the string argument provided isn't in the expected format.

When Does It Occur?

This exception commonly appears when using parsing methods like:

  • Integer.parseInt("abc") — string contains non-numeric characters
  • Double.parseDouble("12.34.56") — invalid decimal format
  • Long.parseLong("") — empty string
  • Integer.parseInt("2147483648") — value exceeds type limits
try {
    int age = Integer.parseInt(userInput);
    System.out.println("Age: " + age);
} catch (NumberFormatException e) {
    System.out.println("Invalid number format: " + e.getMessage());
}

Why This Exception Matters

Think of it like translating words between languages—sometimes a word in one language doesn't exist in another. Similarly, not every string can be translated into a number. The string "123" translates perfectly to the number 123, but "12abc3" has no valid numeric equivalent.

Handling the Exception

When accepting user input or reading external data, always anticipate that conversion might fail. Use try-catch blocks to handle NumberFormatException gracefully, providing meaningful feedback or default values instead of crashing your program.

String input = "not-a-number";
try {
    int value = Integer.parseInt(input);
} catch (NumberFormatException e) {
    System.out.println("Please enter a valid integer");
    // Provide default or re-prompt user
}

Key Takeaway: NumberFormatException signals that a string cannot be converted to the requested numeric type; always handle it when parsing untrusted or user-provided strings to prevent runtime crashes.