In a loop where thousands of items are being converted from String to int, should one check if a string is empty before calling Integer.parseInt or should directly rely on the NumberFormatException to move to the next?
3 Answers
If empty strings are exceptions (i.e. it should not happen) in your data then it is accepted practice to not check them and just let the exception system handle it.
If empty strings are possible (even if rare) and would mean something (e.g. "" -> "0") then you should check.
The bottom line is you should not use exceptions to control program flow.
2 Comments
parseInt et al as kind of a special case. There's no function you can call first (e.g. willParse) so in order to avoid throwing the exception, you have to implement quite a few checks yourself - the logic isn't quite as simple as one might think. I tend to think it's easier just to catch the exception. This question has some interesting discussion about it.Integer.parseInt has been a problem for a long time. It has been discussed in many places. I was hoping only to focus on empty strings here as the OP stated.No.
You have to catch the NumberFormatException anyway, so adding an additional check just adds more code a reader has to wade through for no functional benefit.
(I'm assuming from the question you do want to check if it's invalid in any case, and not just check if its empty. If you just want to check whether it's empty and not whether it's generally invalid, then obviously just use isEmpty() and don't catch anything at all!)
Yes, exceptions should not normally be used for control flow - but catching a NumberFormatException to check if a String is a valid int or not is a reasonably well understood exception to this rule.
4 Comments
isParseable() method on Integer or similar that we'd use instead - but there's not, so this is the only reasonable way.Well, it all depends:
- if each string in the source collection is expected to be a valid integer when parsed then I'd say don't check if it's not empty as it will probably end up hiding a bug.
- if you expect some strings to be empty and others to be valid integers then yes you'll need to check if it's not empty before parsing to an integer otherwise you'll get an exception.
- if the source collection could contain both valid integers as well as strings that cannot be parsed into an integer, then you'll need to perform some validation prior to parsing the strings.
NumberFormatExceptionanyway.