If you get NumberFormatException in Java, it is highly probable because of the following reasons. This article will uncover the NumberFormatException, how you are getting it and what you should do to handle the exception properly.
What is NumberFormatException
The NumberFormatException is an unchecked Java exception which happens when there is incorrect string input converted to a numeric value. When the input is wrong, NumberFormatException is thrown to inform the user that the conversion requires a correct input and the transformation did not happen. For example, the NumberFormatException is thrown when a numerical string is parsed to an integer, but the string contains also space.
As the NumberFormatException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor. However, when in doubt of input correctness, it should be handled in code using a try-catch block.
NumberFormatException Example
Let’s take a look at the simple example of NumberFormatException being thrown:
public class NumberFormatExceptionExample {
public static void main(String args[]) {
int orderNumber = Integer.parseInt("Order 66");
System.out.println(orderNumber);
}
}
The above code will throw NumberFormatException. While pure input of string “66” is a valid input, a string with non-numerical characters like “Order 66” is unsuitable for creating a number.
Exception in thread "main" java.lang.NumberFormatException: For input string: "Order 66"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:6)
8 Different Ways How To Get NumberFormatException
There are various causes for throwing NumberFormatException, and the improper conversion of invalid input mainly causes them. Here is a list of different ways how to get NumberFormatException:
1. Input string is empty:
Integer.parseInt("");
2. Input string is null:
Integer.parseInt(null);
3. Input string with non-numeric data:
This case has several different options why it can happen.
a. Input string contains space character:
Integer.parseInt("66 66");
b. Input string contains non-numeric character:
Integer.parseInt("Sixty");
c. Numeric input with non-numeric character in input string
Integer.parseInt("Catch22");
4. Input string with inappropriate symbols in it:
Double.parseDouble("66,12345");
5. Input string with leading or tailing white space
Integer randomExample = new Integer(" 12345 ");
Integer, Long, Short, Byte throw NumberFormatException; Double, Float does not.
6. Mismatch of data type between input string and the target data type
Integer.parseInt("12.34");
7. Input string exceeding the range of the target data type
Integer.parseInt("2147483648");
The example shown above is a case of NumberFormatException upon placing a numeric input string exceeding the range of the target data type, which is in our case Integer class object. The maximum range for Integer class object is from -2_147_483_648 to 2_147_483_647.
How to handle NumberFormatException
The NumberFormatException is an unchecked exception in Java. Therefore it can be handled as any other Java exception by wrapping critical code to try-catch block.
Look at the following example of catching NumberFormatException with a try-catch block:
public class NumberFormatExceptionExample {
public static void main(String args[]) {
String userInput = "Order 66";
Optional<Integer> orderNumber = processOrder(userInput);
if (orderNumber.isPresent()) {
System.out.println("Execute order " + orderNumber.get());
} else {
System.out.println("Unrecognized order number. Please try again.");
}
}
public static Optional<Integer> processOrder(String userInput) {
try {
int order = Integer.parseInt(userInput);
return Optional.of(order);
} catch (NumberFormatException ex) {
System.out.println("Order exception: Invalid user input!");
}
return Optional.empty();
}
}
Depending on the requirements of the application, take necessary action. For example, log the exception with an appropriate message or return an empty Optional object if you are using at least Java 8. Like in the example above, wrapping the code in try-catch blocks allows the program to continue execution after the code throws the exception.
Output:
Order exception: Invalid user input!
Unrecognized order number. Please try again.
Conclusion
This article led us to explain what NumberFormatException and how to handle it. It also showed over seven different ways how the NumberFormatException can occur and how we can defensively take care of it.
Do you know NumberFormatException? In what case did it throw to you? Do you have your trick, or do you see another way how to handle NumberFormatException? Let us know in the comments below the article. We would like to hear your ideas and stories.