[Solved] java.lang.NumberFormatException: For input string “AB.C”

NumberFormatException is runtime Unchecked Exception. It’s sub class of IllegalArgumentsException. Generally it throws to indicate that the application has attempted to convert a String to one of the numeric types, but that the string does not have the appropriate format.

Constructors

  • NumberFormatException() : Constructs a NumberFormatException with no detail message.
  • NumberFormatException(String s) : Constructs a NumberFormatException with the specified detail message.

Example 1

In below example asking to enter integer value from console and that value further use for other steps. This example will throw ArithmaticException when enter value as 0 or throw NumberFormatException for any value except integer.

import java.util.Scanner;

public class NumberFormatExceptionExample {

public static void main(String[] args) {
System.out.println("Please enter a integer value :");
Scanner scn = new Scanner(System.in);
try
{
int n = Integer.parseInt(scn.nextLine());
if (99%n == 0)
System.out.println(n + " is a factor of 99");
}
catch (ArithmeticException ex)
{
System.out.println("Arithmetic " + ex);
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}
}
}

Output

Please enter a integer value :
3.56
Number Format Exception java.lang.NumberFormatException: For input string: "3.56"

Example 2

Here issue is passing string as non numeric value while parsing for Integer will throw NumberFormatException.

try
{
int age=Integer.parseInt("Twenty");}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}

Example 3

Here issue is passing string as numeric  value which out MAX range of integer that’s what throw NumberFormatException. In this case instead of using Integer.parseInt() use Long.parseLong(). 

try{
int phoneNumber=Integer.parseInt("1234567890");
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}

Solutions

Here are some common solutions for NumberFormatException:

  • Always check for numeric before using statement Integer.parseInt().
  • If expectation is big numeric value always use Long.parseLong().

References

https://docs.oracle.com/javase/7/docs/api/java/lang/NumberFormatException.html

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:

 

 

 

 

 

Advertisements

This site uses Akismet to reduce spam. Learn how your comment data is processed.