NumberFormatException in Java

In this article, we will learn what is NumberFormatException in Java, its common causes, example, and how to handle NumberFormatException.

What is NumberFormatException? 

NumberFormatException is a runtime exception in Java that signals an attempt to convert a string into a number, but the string does not have the appropriate format. This typically occurs when using methods like Integer.parseInt() or Double.parseDouble() on strings that don't represent valid numbers. 

NumberFormatException Class Diagram

Common Causes

User Input: Users may input data that looks numeric but isn't valid. For instance, "123.45.67" might appear at a glance to be a number, but it's not a valid format. 

Data Import: When importing data from external sources, there's always the risk of malformed data.

Strings with Non-Numeric Characters: Attempting to parse strings with characters that aren't valid in numbers, e.g., "12A34" or "12.34.56".

Java NumberFormatException Example

In the below example, we are trying to parse the "100ABCD" string into an integer leads to NumberFormatException:
package com.javaguides.corejava;

public class NumberFormatExceptionExample {

    public static void main(String[] args) {

        String str1 = "100ABCD";
        try {
            int x = Integer.parseInt(str1); // Converting string with inappropriate format
            int y = Integer.valueOf(str1);
        } catch (NumberFormatException e) {
            System.err.println("NumberFormatException caught!");
NumberFormatException caught!
java.lang.NumberFormatException: For input string: "100ABCD"
 at java.lang.NumberFormatException.forInputString(
 at java.lang.Integer.parseInt(
 at java.lang.Integer.parseInt(
 at com.javaguides.corejava.NumberFormatExceptionExample.main(

Handling NumberFormatException 

Validation: Before attempting to parse a string as a number, validate its format using regular expressions or other validation techniques. 

Use Third-Party Libraries: Libraries like Apache Commons Lang provide more lenient parsing methods which can handle different number formats. 

Graceful Error Messages: If parsing user input, provide a clear error message so they can correct their input. 

Try-Catch: As with most exceptions, a try-catch block is your best bet for catching and handling the exception effectively. 

Best Practices 

  • Avoid blind trust in external data. 
  • Always assume the possibility of incorrect formats and validate data before processing. 
  • Consider setting up input masks or formats in user interfaces to guide users into inputting data in the correct format. 
  • When parsing multiple strings in a loop, it might be beneficial to log the failures but continue processing valid entries instead of terminating the whole process.