148

Possible Duplicate:
Java: Good way to encapsulate Integer.parseInt()
how to convert a string to float and avoid using try/catch in java?

C# has Int.TryParse: Int32.TryParse Method (String, Int32%)

The great thing with this method is that it doesn't throw an exception for bad data.

In java, Integer.parseInt("abc") will throw an exception, and in cases where this may happen a lot performance will suffer.

Is there a way around this somehow for those cases where performance is an issue?

The only other way I can think of is to run the input against an regex, but I have to test to see what is faster.

10
  • 1
    Unfortunately, no. See this question for more details: stackoverflow.com/questions/1369077/… Commented Dec 5, 2011 at 21:20
  • 13
    @MartijnCourteaux: "Throwing Exceptions doesn't reduce performance": False. "Regex will definitely be slower": True. Commented Dec 5, 2011 at 21:21
  • 4
    @Martijn: throwing lots of exceptions can definitely be bad for performance (though I have a hard time coming up with a use case where you have to parse lots of data of which a large percentage is malformed). Commented Dec 5, 2011 at 21:23
  • 2
    @StriplingWarrior Actually you are incorrect. Throwing an Exception is not expensive, building the stack trace is. Commented Dec 5, 2011 at 21:23
  • 1
    @Woot4Moo: This answer indicates that it's roughly 66x slower than just doing a loop, without printing a stack trace. That may not be vastly slower once you take into account the cost of actually parsing the string, but it's not something to scoff at either. stackoverflow.com/a/299315/120955 Commented Dec 5, 2011 at 21:31

3 Answers 3

105

No. You have to make your own like this:

public int tryParseInt(String value, int defaultVal) {
    try {
        return Integer.parseInt(value);
    } catch (NumberFormatException e) {
        return defaultVal;
    }
}

...or

public Integer parseIntOrNull(String value) {
    try {
        return Integer.parseInt(value);
    } catch (NumberFormatException e) {
        return null;
    }
}
Sign up to request clarification or add additional context in comments.

10 Comments

This doesn't return the parsed integer. How would they do that?
You use that as a method to determine if it is safe to parse the int. Notice how the MSDN version also returns a boolean.
So now we're not only adding the overhead of throwing and catching an exception, but we're also performing the actual parsing twice?
The TryParse methods in C# use an "out" parameter (essentially a pointer) to set a target numeric variable IF the parse is successful, the success of which is indicated by the boolean return value of the method. Java does not have an equivalent to the out parameter, thus the need for the if logic shown in this answer. msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx
Or use a default value... since, if we don't want an exception to take care of the problem, that's usually where we'll end up anyway. tryParseInt(String value, int defaultValue). See Java 8's Map.getOrDefault(...)
|
35

Apache Commons has an IntegerValidator class which appears to do what you want. Java provides no in-built method for doing this.

See here for the groupid/artifactid.

Code sample: (slightly verbose to show functionality clearly)

private boolean valueIsAndInt(String value) {
    boolean returnValue = true;
    if (null == new org.apache.commons.validator.routines.IntegerValidator().validate(value)) {
        returnValue = false;
    }
    return returnValue;
}

Comments

2

Edit -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex. I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.

Anyway, I'd just do this:

public Integer tryParse(Object obj) {
  Integer retVal;
  try {
    retVal = Integer.parseInt((String) obj);
  } catch (NumberFormatException nfe) {
    retVal = 0; // or null if that is your preference
  }
  return retVal;
}

8 Comments

that is bad, 0 is an acceptable return value and is therefore impossible to deduce an exception or a valid entry.
Exceptions are very slow, because they unwind the stack and look for any finally blocks. Exceptions should be avoided for validation. They are there for reporting serious problems, i.e. exceptions should be exceptional.
I think that returning null is the best approach as this more closely resembles the requested question of implementing TryParse which returns a boolean. To get around exceptions the Integer.parseInt implementation could be mirrored to return null instead of throwing NumberFormatException.
Also, the retVal is completely useless...
downvote. 0 is a valid integer
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.