Way2Java

NumberFormatException

NumberFormatException is an unchecked exception thrown by parseXXX() methods when they are unable to format (convert) a string into a number.

Sometimes, in Java coding, we get input (like from command-line arguments and text field) from the user in the form of string. To use the string in arithmetic operations, it must be converted (parsed) into data types. This is done by parseXXX() methods of wrapper classes.

Following is the hierarchy of NumberFormatException.

Object –> Throwable –> Exception –> RuntimeException –> NumberFormatException

Full hierarchy of exceptions is available at "Hierarchy of Exceptions – Checked/Unchecked Exceptions".

String str1= “10”;
System.out.println(str1); // prints 10

The str1 represents 10, but it is in the form of string. Printing is no problem, but is not compatible for arithmetic manipulations. Following statements converts str1 into int form.

int x = Integer.parseInt(str1);
System.out.println(x*x); // prints 100

parseInt() is a method of Integer class which formats string into int data type. This is fine and works well. But what about the following? Suppose the user enters ten instead of numeric value 10 (remember, user, who uses your software product, is always innocent as he is not computer background having MCA or B.Tech (CSC) like a clerk in a bank). Is it possible to parseInt() method to parse string ten? Not possible and being unable to format, it throws "NumberFormatException". Following program illustrates.

public class NFE
{
  public static void main(String args[])
  {
    String str1= "10";
    int x = Integer.parseInt(str1);
    System.out.println(x*x);    // prints 100

    try
    {
      String str2= "ten";
      int y = Integer.parseInt(str2);
    }
    catch(NumberFormatException e)
    {
      System.err.println("Unable to format. " + e);
    }
  }
}

As str2 cannot be formatted into a number, the JVM throws NumberFormatException and we caught it in catch block. Handling exception is a robust way of developing code.