I need to have a validation function, boolean isFloat(String)
, to check if a given string can be directly converted to an integer. There are at least two approaches on base of Checking If a String is Numeric in Java:
in plain Java:
isFloat(String f) { if (strNum == null) { return false; } try { Float.parseFloat(strNum); } catch (NumberFormatException nfe) { return false; } return true; }
in regular expression, hereby I don't list the code
The first approach is more strict forward and easy to understand, whereas one of my colleagues said throwing exception might the whole stack trace, which might affect performance when happening frequently. The second approach might be error-prone as we always need to think about how the expression is formed.
Question: Is the impract of throwing and catching the whole stack trace of an exception really that big?