How to Handle NumberFormatException in Java

Quite often in our code we get input from the user in the form of String, or maybe we save user input in String format. As example, I often work with metadata table (which normally contains key and value). And the value is in String. If the program need to do arithmetic operation or calculation, then this String need to be converted (parsed) into a numeric data types. One of the way to do conversion, is by using parseXXX() methods of wrapper classes (Convert String to int, Convert String to long, Convert String to double). NumberFormatException thrown when the application has attempted to convert a string to one of the numeric types, but the string does not have the appropriate format.

Following is the hierarchy of NumberFormatException:

Object ->Throwable ->Exception ->RuntimeException ->IllegalArgumentException ->NumberFormatException

Here an example of catching NumberFormatException in the program:

NumberFormatExceptionExample.java
public class NumberFormatExceptionExample {

    public static void main(String[] args) {
        String s1 = "12";
        int i1 = Integer.parseInt(s1);

        String s2 = "9L";
        long l1 = Long.parseLong(s1);
        System.out.println(i1 * l1);    // 100

        try {
            int i3 = Integer.parseInt(s2);
        } catch (NumberFormatException e) {
            System.err.println("Unable to format. " + e);
        }
    }
}

/*
Output:
-------
144
Unable to format. java.lang.NumberFormatException: For input string: "9L"
 */
                    

String "9L" is valid for long but not valid for an int, that's why NumberFormatException is thrown. So we can say, if the input is not numeric or "valid" format, than the method which try to convert String to number - in our case: Integer.parseInt() - will throw java.lang.NumberFormatException.

Here some common reason that commonly encounter in a String that causing NumberFormatException:

  • Null String: Since String is an object, it's possible to have null value. If we passing this null value to any parseXXX() methods, it'll throw NumberFormatException. (Tips: Check for null String)
  • Empty String: Similar like null String, String also can be empty. (Tips: Check for empty String)
  • "null" String: It's maybe seems stupid, but we can encounter "null" String which is neither null or empty. (Tips: Check for String with "null" value, correct the program logic why "null" value happen)
  • String with whitespace: Either leading or trailing space, tab character, etc, unwanted whitespace can lead to NumberFormatException during conversion (Tips:Trim or strip your String, sanitize our string input)
  • Alphanumeric String: Other than numeric character, some characters maybe allowed in String format - like '.' for decimal, prefix 'D" or 'd' for double, etc. But if the String contains unaccepted character, it will thrown NumberFormatException (Tips: Sanitize our string input)
try {
    System.out.println(Byte.parseByte(null));
} catch (NumberFormatException e) {
    System.out.println(e.getMessage());  // null
}

try {
    System.out.println(Short.parseShort(""));
} catch (NumberFormatException e) {
    System.out.println(e.getMessage());  // For input string: ""
}

try {
    System.out.println(Integer.parseInt("null"));
} catch (NumberFormatException e) {
    System.out.println(e.getMessage());  // For input string: "null"
}

try {
    System.out.println(Double.parseDouble(" 123.45"));   // pass - 123.45
    System.out.println(Double.parseDouble(" 123.45 "));  // pass - 123.45
    System.out.println(Long.parseUnsignedLong("123.45 "));
} catch (NumberFormatException e) {
    System.out.println(e.getMessage());  // For input string: "123.45 "
}

try {
    System.out.println(Integer.parseUnsignedInt("+123"));  // pass - 123
    System.out.println(Integer.parseUnsignedInt("-123"));  
} catch (NumberFormatException e) {
    System.out.println(e.getMessage());  // Illegal leading minus sign on unsigned string -123.
}

try {
    System.out.println(Integer.parseUnsignedInt("123I"));
} catch (NumberFormatException e) {
    System.out.println(e.getMessage());  // For input string: "123I"
}
                    

Conclusion: Handling NumberFormatException

NumberFormatException is one of the core exception and one of the most common errors in Java application after NullPointerException (and NoClassDefFoundError). It's an unchecked exception, which will not checked during compilation time. As a RuntimeException, it will thrown during runtime.

Handling of exception is one of the most important practice for writing secure and reliable Java programs. The only way to solve this exception is to make sure the data is correct, we must sanitize the input (or reject it) if it's not in our accepted format. On another hand, we must catch this exception whenever we are trying to convert a String into number.