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

Mocktagish picture Mocktagish · Jan 8, 2012 · Viewed 31.3k times · Source

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;

Answer

Dave Newton picture Dave Newton · Jan 8, 2012

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