Check whether a string is parsable into Long without try-catch?

Serg picture Serg · Apr 1, 2010 · Viewed 72.2k times · Source

Long.parseLong("string") throws an error if string is not parsable into long. Is there a way to validate the string faster than using try-catch? Thanks

Answer

Roman picture Roman · Apr 1, 2010

You can create rather complex regular expression but it isn't worth that. Using exceptions here is absolutely normal.

It's natural exceptional situation: you assume that there is an integer in the string but indeed there is something else. Exception should be thrown and handled properly.

If you look inside parseLong code, you'll see that there are many different verifications and operations. If you want to do all that stuff before parsing it'll decrease the performance (if we are talking about parsing millions of numbers because otherwise it doesn't matter). So, the only thing you can do if you really need to improve performance by avoiding exceptions is: copy parseLong implementation to your own function and return NaN instead of throwing exceptions in all correspondent cases.