Blog |

How to Handle the NumberFormat Exception in Java

How to Handle the NumberFormat Exception in Java
Table of Contents

The NumberFormatException is an unchecked exception in Java that occurs when an attempt is made to convert a string with an incorrect format to a numeric value. Therefore, this exception is thrown when it is not possible to convert a string to a numeric type (e.g. int, float). For example, this exception occurs if a string is attempted to be parsed to an integer but the string contains a boolean value.

Since the NumberFormatException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor. It can be handled in code using a try-catch block.

 

What Causes NumberFormatException

There can be various cases related to improper string format for conversion to numeric values. Some of them are:

Null input string

Integer.parseInt(null);

Empty input string

Integer.parseInt("");

Input string with leading/trailing whitespaces

Integer myInt = new Integer(" 123  ");

Input string with inappropriate symbols

Float.parseFloat("1,234");

Input string with non-numeric data

Integer.parseInt("Twenty Two");

Alphanumeric input string

Integer.parseInt("Twenty 2");

Input string exceeding the range of the target data type

Integer.parseInt("12345678901");

Mismatch of data type between input string and the target data type

Integer.parseInt("12.34");

 

NumberFormatException Example

Here is an example of a NumberFormatException thrown when attempting to convert an alphanumeric string to an integer:

public class NumberFormatExceptionExample {
    public static void main(String args[]) {
        int a = Integer.parseInt("1a");
        System.out.println(a);
    }
}

In this example, a string containing both numbers and characters is attempted to be parsed to an integer, leading to a NumberFormatException:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1a"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:3)

Such operations should be avoided where possible by paying attention to detail and making sure strings attempted to be parsed to numeric values are appropriate and legal.

 

How to Handle NumberFormatException

The NumberFormatException is an exception in Java, and therefore can be handled using try-catch blocks using the following steps:

  • Surround the statements that can throw an NumberFormatException in try-catch blocks
  • Catch the NumberFormatException
  • Depending on the requirements of the application, take necessary action. For example, log the exception with an appropriate message.

The code in the earlier example can be updated with the above steps:

public class NumberFormatExceptionExample {
    public static void main(String args[]) {
        try {
            int a = Integer.parseInt("1a");
            System.out.println(a);
        } catch (NumberFormatException nfe) {
            System.out.println("NumberFormat Exception: invalid input string");
        }
        System.out.println("Continuing execution...");
    }
}

Surrounding the code in try-catch blocks like the above allows the program to continue execution after the exception is encountered:

NumberFormat Exception: invalid input string
Continuing execution...

 

Track, Analyze and Manage Errors with Rollbar

Rollbar in action

Finding exceptions in your Java code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring, tracking and triaging, making fixing Java errors and exceptions easier than ever. Sign Up Today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape