NumberFormatException in Java and how to prevent it

NumberFormatException occurs in Java when we are trying to convert string into some numeric type but string is not in the correct format.

It usually occurs when we parse string to integer, double, long etc datatypes but string is not present in correct format.

Let us see an example code :

public class Tech4Humans {

public static void main(String[] args) {

		System.out.println("Execution Started");
		
		//we are passing inappropriate string to be parsed into integer.
		int num = Integer.parseInt("123a");
		System.out.println(num);
		
		System.out.println("Execution ended");
	}

}

Output

Execution Started
Exception in thread "main" java.lang.NumberFormatException: For input string: "123a"
	at java.lang.NumberFormatException.forInputString(Unknown Source)
	at java.lang.Integer.parseInt(Unknown Source)
	at java.lang.Integer.parseInt(Unknown Source)
	at Tech4Humans.main(Tech4Humans.java:8)

Since ‘123a’ cannot be converted to integer hence it throws NumberFormatException.

How to prevent NumberFormatException

To prevent the NumberFormatException we can surround the parse code with try catch block, so that even if the exception is thrown it can be handled with appropriate message and the program flow completes.

Let us prevent the exception in above code:

public class Tech4Humans {

public static void main(String[] args) {

		System.out.println("Execution Started");
		
		try 
		{
			int num = Integer.parseInt("123a");
			System.out.println(num);
		}
		catch(NumberFormatException e) {
			System.out.println("Please enter appropriate string for parsing");
		}
		
		System.out.println("Execution ended");
	}
}

Output

Execution Started
Please enter appropriate string for parsing
Execution ended

As you can see we displayed an appropriate message to handle NumberFormatException and also program execution does not break in between.

Leave a Comment