This question is a follow-up to Does java have a int.tryparse that doesn't throw an exception for bad data?, which is marked as a duplicate of Java: Good way to encapsulate Integer.parseInt().
Both questions seem to be more about how to catch the
The best answer I have found so far without writing my own integer parsing code or using flaky regexes is to use Guava's
Ints.tryParse(String string) or
Longs.tryParse(String string, int radix) method.
Longs.tryParse() is basically a reimplementation of the standard Java
Long.parseLong(), but returning
null or a
Long instead of throwing a
NumberFormatException. This seems to me to be the best approach: it is as efficient at parsing as
Long.parseLong() but handles the error case more efficiently.