Handle NumberFormatException Unchecked in Java



The NumberFormatException is a class that represents an unchecked exception thrown by parseXXX() methods when they are unable to format (convert) a string into a number. Here, the parseXXX() is a group of Java built-in methods that are used to convert string representations of numbers into their corresponding primitive data types.

Causes for NumberFormatException in Java

The NumberFormatException extends IllegalArgumentException class of java.lang package. It can be thrown by many methods/constructors of the classes. Following are some of them:

Example: Throwing NumberFormatException

In the example given below, we pass a non-numeric character to the Integer.parseInt() method.

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

Output

When you execute the code, it will display the following error message:

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 Java using the following ways:

  • Place the code that can cause NumberFormatException within the try block and handle it in the corresponding catch block.
  • Another way of handling the exception is the use of the throws keyword.

Example: Handling NumberFormatException

Let's see an example of Java code that shows how to handle NumberFormatException.

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

Output

On running the above example, the method intParsingMethod() throws the exception object:

NumberFormatException! Check your input
Updated on: 2025-05-27T10:50:11+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements