0

I have a lot of code that gathers user input and parses it, I want to parse integer values without throwing exceptions.

My current tryParseInt() function is code is simple:

public static Integer tryParseInt( String text )
{
    if(text == null)
        return null;

    try
    {
        return new Integer( text.trim() );
    }
    catch ( NumberFormatException e )
    {
        return null;
    }
}

But i am getting lots of NumberFormatExceptions and i am worried becouse that may impact my app performance. Can anyone suggest me on best practice for parsing user inputs.

Thank you

ductran
  • 10,043
  • 19
  • 82
  • 165
Ivan Pavić
  • 528
  • 4
  • 22
  • If you get a lot of NumberFormatExceptions, clean data from non-numeric symbols before parsing – Max77 Jul 03 '15 at 09:13
  • 1
    There are lots of articles around that topic. I prefer [this one](http://stackoverflow.com/a/1369131/1389444) – Patrik Jul 03 '15 at 09:48

3 Answers3

3

You can go with regex as it is more fail proof

 public static Integer tryParseInt(String text) {
    if (text != null && !text.isEmpty()) {
        if (text.trim().matches("[0-9]+")) {
            return Integer.valueOf(text.trim());
        }
    }
    return null;
}
Madhan
  • 5,750
  • 4
  • 28
  • 61
2

This is a very helpful experiment and indeed my experience is removing exceptions is better for performance

Viraj Nalawade
  • 3,137
  • 3
  • 28
  • 44
1

If you are getting a lot of NumberFormatExceptions, you might consider checking the parsing input before the actual parsing.

BTW the return new Integer( text.trim() ); is not very efficient as you will be allocating a lot of unnecessary objects (in the range from -128 to 127).

public static Integer tryParseInt(String text) {
    if(text == null)
        return null;

    try {
        return Integer.valueOf(text.trim());
    }
    catch (NumberFormatException e) {
        return null;
    }
}
Crazyjavahacking
  • 9,343
  • 2
  • 31
  • 40