Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to avoid parseInt throwing a NumberFormatException for input string: ""

When I run parseInt:

Integer.parseInt(myString);

it throws:

NumberFormatException: For input string: ""

Does this mean I have do something like this?

if(StringUtils.isNotBlank(myString))
  return Integer.parseInt(myString);
else
 return 0;
like image 297
Mocktagish Avatar asked Jan 08 '12 20:01

Mocktagish


People also ask

How do I fix Java Lang NumberFormatException for input string?

To avoid this error, you should trim() the input string before passing it to parse methods like the parseInt() or parseFloat().

How do you overcome NumberFormatException?

The NumberFormatException is an exception in Java, and therefore can be handled using try-catch blocks using the following steps: Surround the statements that can throw an NumberFormatException in try-catch blocks. Catch the NumberFormatException. Depending on the requirements of the application, take necessary action.

How do I resolve Java Lang NumberFormatException null?

NumberFormatException: For input string: "null" is specifically saying that the String you receive for parsing is not numeric and it's true, "null" is not numeric. Many Java methods which convert String to numeric type like Integer. parseInt() which convert String to int, Double.

Which of the following statement will cause a NumberFormatException?

The NumberFormatException is thrown when we try to convert a string into a numeric value such as float or integer, but the format of the input string is not appropriate or illegal.

What exemption does parseInt throw?

The parseInt method is to convert the String to an int and throws a NumberFormatException if the string cannot be converted to an int type.

What happens if you try to parseInt a string?

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .


2 Answers

Yes, but: Wrap it in a thin method (and eliminate the redundant else), or use an existing implementation, like Commons Lang's NumberUtils.toInt(str, defaultValue):

NumberUtils.toInt(myString, 0);

This method handles null values and conversion failures.

Writing the same thing on your own is straight-forward:

  • Check for null, and/or...
  • ...Wrap the NumberFormatExtension exception
like image 113
Dave Newton Avatar answered Oct 19 '22 02:10

Dave Newton


Well, you could use the conditional operator instead:

return StringUtils.isNotBlank(myString) ? Integer.parseInt(myString) : 0;

If you need to do this in multiple places, you'd probably want to put this into a separate method. Note that you should also consider situations where myString is null, or contains non-numeric text.

like image 29
Jon Skeet Avatar answered Oct 19 '22 02:10

Jon Skeet