How To Handle NumberFormatException in Java

Mouad Oumous
The Fresh Writes
Published in
10 min readFeb 6, 2023
src

· What is an exception?
· NumberFormatException
Hierarchy
Syntax
What Causes NumberFormatException
How to handle NumberFormatException
· Examples to Implement NumberFormatException in Java
Example #1
Example #2
· Avoid NumberFormatException

What is an exception?

  • In its most general sense, an exception is a problem that appears at run-time that cannot be anticipated by a general Java program and needs to be specially handled by the programmer.
  • Common Types of Exception: FileNotFoundException, ClassNotFoundException, IndexOutOfBoundsException
NumberFormatException

NumberFormatException

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.

The NumberFormatException is a built-in class in java that is defined in the Java.lang.NumberFormatException package. The IllegalArgumentException class is a superclass of the NumberFormatException as it is an unchecked exception, so it is not forced to handle and declare it.

In a Java program, sometimes the user input is accepted through command-line arguments as a text field in the form of a string. And to use this string in some arithmetic operations, it should first parse or convert into data types(specific numeric type) by using the parseXXX() functions of the wrapper classes

NumberFormatException is thrown when it is not possible to convert a string to a numeric type (e.g. int, float),because of the format of an input string is illegal and not appropriate. For example, this exception occurs if a string is attempted to be parsed to an integer but the string contains a boolean value.

Hierarchy

The hierarchy of NumberFormatException class is:

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

Syntax

The following is the declaration for java.lang.NumberFormatException class.

public class NumberFormatException extends IllegalArgumentException implements Serializable
{
// Constructors of the NumberFormatException class
}

The above is the syntax of the NumberFormatException, where it is extended to the:

IllegalArgumentException class and implements Serializabletion.

What Causes NumberFormatException

The NumberFormatException occurs when an attempt is made to convert a string with improper format into a numeric value. That means, when it is not possible to convert a string in any numeric type (float, int, etc), this exception is thrown. It is a Runtime Exception (Unchecked Exception) in Java.It is a subclass of IllegalArgumentException class. To handle this exception, trycatch block can be used.

While operating upon strings, there are times when we need to convert a number represented as a string into an numeric type. The method generally used to convert String to Integer in Java is parseXXXX().

The NumberFormatException can be thrown by many methods/constructors in the classes of java.lang package. Following are some of them.

  • public static int parseInt(String s) throws NumberFormatException
  • public static Byte valueOf(String s) throws NumberFormatException
  • public static byte parseByte(String s) throws NumberFormatException
  • public static byte parseByte(String s, int radix) throws NumberFormatException
  • public Integer(String s) throws NumberFormatException
  • public Byte(String s) throws NumberFormatException

….

lets take parseInt() as an example

Usage of parseInt() method: As we already know there are two variants of this method namely as follows to get a better understanding

public static int parseInt(String s) throws NumberFormatException
This function parses the string argument as a signed decimal integer.
public static int parseInt(String s, int radix) throws NumberFormatException
This function parses the string argument as a
signed integer in the radix specified by the second argument.

In simple words, both methods convert the string into its integer equivalent. The only difference being is that of the parameter radix. The first method can be considered as an equivalent of the second method with radix = 10 (Decimal).

Constructors:

  1. public NumberFormatException(): Constructs a NumberFormatException with no detail message.
  2. public NumberFormatException(String msg): Constructs a NumberFormatException with the detail message ‘msg’

There are situations defined for each method, where it can throw a NumberFormatException. For instance, public static int parseInt(String s) throws NumberFormatException when

  • String s is null or length of s is zero.
  • If the String s contains non-numeric characters.
  • Value of String s doesn’t represent an Integer.

The input string is null

Integer.parseInt("null") ;

The input string is empty

Float.parseFloat(“”) ;

Non-Numeric Data Passed to Constructor

Let’s look at an attempt to construct an Integer or Double object with non-numeric data.

Both of these statements will throw NumberFormatException:

Integer aIntegerObj = new Integer("one");
Double doubleDecimalObj = new Double("two.2");"); background-repeat: no-repeat; background-position: center center; background-color: rgb(99, 177, 117);">Copy

Let’s see the stack trace we got when we passed invalid input “one” to the Integer constructor in line 1:

Exception in thread "main" java.lang.NumberFormatException: For input string: "one"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.<init>(Integer.java:867)
at MainClass.main(MainClass.java:11)"); background-repeat: no-repeat; background-position: center center; background-color: rgb(99, 177, 117);">Copy

It threw NumberFormatException. The Integer constructor failed while trying to understand input using parseInt() internally.

The Java Number API doesn’t parse words into numbers, so we can correct the code by simply by changing it to an expected value:

Integer aIntegerObj = new Integer("1");
Double doubleDecimalObj = new Double("2.2");

Parsing Strings Containing Non-Numeric Data

Similar to Java’s support for parsing in the constructor, we’ve got dedicated parse methods like parseInt(), parseDouble(), valueOf(), and decode().

If we try and do the same kinds of conversion with these:

int aIntPrim = Integer.parseInt("two");
double aDoublePrim = Double.parseDouble("two.two");
Integer aIntObj = Integer.valueOf("three");
Long decodedLong = Long.decode("64403L");"); background-repeat: no-repeat; background-position: center center; background-color: rgb(99, 177, 117);">Copy

Then we’ll see the same kind of erroneous behavior.

And, we can fix them in similar ways:

int aIntPrim = Integer.parseInt("2");
double aDoublePrim = Double.parseDouble("2.2");
Integer aIntObj = Integer.valueOf("3");
Long decodedLong = Long.decode("64403");

The input string with non-numeric data

Double.parseDouble(“ThirtyFour”);

The input string is alphanumeric

Integer.valueOf(“31.two”);

Passing Strings With Extraneous Characters

Or, if we try to convert a string to a number with extraneous data in input, like whitespace or special characters:

Short shortInt = new Short("2 ");
int bIntPrim = Integer.parseInt("_6000");"); background-repeat: no-repeat; background-position: center center; background-color: rgb(99, 177, 117);">Copy

Then, we'll have the same issue as before.

We could correct these with a bit of string manipulation:

Short shortInt = new Short("2 ".trim());
int bIntPrim = Integer.parseInt("_6000".replaceAll("_", ""));
int bIntPrim = Integer.parseInt("-6000");"); background-repeat: no-repeat; background-position: center center; background-color: rgb(99, 177, 117);">Copy

Note here in line 3 that negative numbers are allowed, using the hyphen character as a minus sign.

The input string with leading and/or trailing white spaces

Integer abc=new Integer(“  432 “);

The input string with extra symbols

Float.parseFloat(4-236);
Float.parseFloat(4,236);
Float.parseFloat(56*);

Locale-Specific Number Formats

Let’s see a special case of locale-specific numbers. In European regions, a comma may represent a decimal place. For example, “4000,1 ” may represent the decimal number “4000.1”.

By default, we’ll get NumberFormatException by trying to parse a value containing a comma:

double aDoublePrim = Double.parseDouble("4000,1");"); background-repeat: no-repeat; background-position: center center; background-color: rgb(99, 177, 117);">Copy

We need to allow commas and avoid the exception in this case. To make this possible, Java needs to understand the comma here as a decimal.

We can allow commas for the European region and avoid the exception by using NumberFormat.

Let’s see it in action using the Locale for France as an example:

NumberFormat numberFormat = NumberFormat.getInstance(Locale.FRANCE);
Number parsedNumber = numberFormat.parse("4000,1");
assertEquals(4000.1, parsedNumber.doubleValue());
assertEquals(4000, parsedNumber.intValue());

The input string might exceed the range of the datatype storing the parsed string

Integer.parseInt(“1326589741236”);

Data type mismatch between input string value and the type of the method which is being used for parsing

Integer.parseInt("13.26");

Example1

public class NumberFormatExceptionTest {
public static void main(String[] args){
int x = Integer.parseInt("30k");
System.out.println(x);
}
}

Output

Exception in thread "main" java.lang.NumberFormatException: For input string: "30k"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at NumberFormatExceptionTest.main(NumberFormatExceptionTest.java:3)

How to handle NumberFormatException

We can handle the NumberFormatException in two ways

  • Use try and catch block surrounding the code that can cause NumberFormatException.
  • Another way of handling the exception is the use of throws keyword.

Example2

public class NumberFormatExceptionHandlingTest {
public static void main(String[] args) {
try {
new NumberFormatExceptionHandlingTest().intParsingMethod();
} catch (NumberFormatException e) {
System.out.println("We can catch the NumberFormatException");
}
}
public void intParsingMethod() throws NumberFormatException{
int x = Integer.parseInt("30k");
System.out.println(x);
}
}

In the above example, the method intParsingMethod() throws the exception object that is thrown by Integer.parseInt(“30k”) to its calling method, which is the main() method in this case.

Output

We can catch the NumberFormatException

Examples to Implement NumberFormatException in Java

Below are examples to implement:

Example #1

Next, we write the java code to understand the NumberFormatException more clearly with the following example where we create a PrintWriter object by using the PrintWriter class constructor and pass the file name to write in it, as below –

Code:

//package p1;
import java.util.Scanner;
public class Demo
{
public static void main( String[] arg) {
int age;
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter your age : ");
//throws Exception as if the input string is of illegal format for parsing as it as null or alphanumeric.
age = Integer.parseInt(sc.next());
System.out.println("Your age is : " +age);
}
}

Output:

When the user enters “25+”, an output of the above code is:

Please Enter your age: 25+
Exception in thread "main" java.lang.NumberFormatException: For input string: "25+"
at java.lang.NumberFormatException.for InputString (NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Main.main (Main.java:11)

When a user enters not the well-formatted string “25F”, the output is:

 Please Enter your age: 25F 
Exception in thread "main" java.lang.NumberFormatException: For input string: "25F"
at java.lang.NumberFormatException.forInputString (NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Main.main (Main.java:11)

When a user enters a string “Twenty Five”, the output is:

 Please Enter your age: Twenty Five 
Exception in thread "main" java.lang.NumberFormatException: For input string: "Twenty"
at java.lang.NumberFormatException.forInputString (NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Main.main (Main.java:11)

When a user enters a string “null”, the output is:

Please Enter your age: null
Exception in thread "main" java.lang.NumberFormatException: For input string: "null"
at java.lang.NumberFormatException.forInputString (NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Main.main (Main.java:11)

When a user enters string value as a float “40.78”, the output is:

Please Enter your age: 25.5
Exception in thread "main" java.lang.NumberFormatException: For input string: "25.5"
at java.lang.NumberFormatException.forInputString (NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Main.main (Main.java:11)

When the user enters a string “25”, which is a valid string. The output is:

Please Enter your age: 25 :
25
Your age is 25

Explanation: As in the above code, the age value is accepted from the user in string format, which further converts into the integer format by using the Integer.parseInt(sc.next()) function. While the user an illegal input string or not a well-formatted string, the NumberFormatException occurs, it throws, and the program terminates unsuccessfully. So to provide the valid string, it should be taken care that an input string should not be null, check an argument string matches the type of the conversion function used and also check if any unnecessary spaces are available; if yes, then trim it and so all care must be taken.

Example #2

Next, we write the java code to understand the NumberFormatException where we generate the NumberFormatException and handle it by using the try-catch block in the program, as below –

Code:

//package p1;
import java.util.Scanner;
public class Demo
{
public static void main( String[] arg) {
int age;
Scanner sc = new Scanner(System.in);
try
{
System.out.println("Please Enter your age : ");
//throws Exception as if the input string is of illegal format for parsing as it as null or alphanumeric.
age = Integer.parseInt(sc.next());
System.out.println("Your age is : " +age);
} catch(NumberFormatException e)
{
System.out.println("The NumberFormatException occure.");
System.out.println("Please enter the valid age.");
}
}
}

When the user enters a string “23F”, the output is:

Please Enter your age :
23F
The NumberFormatException occure.
Please enter the valid age.

When a user enters a string “23”, the output is:

Please Enter your age :
23
Your age is 23

Explanation: As in the above code try-catch block is used. It is always a good practice to enclose lines of code that can throw an exception in a try-catch block by which it handles the NumberFormatException and prevents it from generating the Exception.

Avoid NumberFormatException

Let’s talk about a few good practices that can help us to deal with NumberFormatException:

  1. Don’t try to convert alphabetic or special characters into numbers — the Java Number API cannot do that.
  2. We may want to validate an input string using regular expressions and throw the exception for the invalid characters.
  3. We can sanitize input against foreseeable known issues with methods like trim() and replaceAll().
  4. In some cases, special characters in input may be valid. So, we do special processing for that, using NumberFormat, for example, which supports numerous formats.

See How To Check If A String Is Numeric

It is a best practice to check if the passed-in string is numeric or not before trying to convert it to integer.

Thanks for reading.Happy learning 😄

Join Mouad Oumous Java WhatsApp Group JOIN

Join Mouad Oumous Telegram Channel JOIN

Do support our publication by following it

Also refer to the following articles

--

--

Mouad Oumous
The Fresh Writes

I'm a blogger on medium, l'm a java and kotlin developer, also an Android Developer I mastered various topics such as Networking, UI , UX, Animation ...