I'm developing a Java Helper Library which has useful methods developers don't want to type out over and over. I'm trying to think of the best way of checking whether a string is a valid number.
I've always just tried something like Integer.parseInt(iPromiseImANumber);
and if it throws an exception then it's not a valid number (integer in this case). I'm thinking that trying to catch an exception isn't good practice. Is there a better way to do this? (I'm thinking a regular expression could do it, but it doesn't seem to be as reliable as the parse
option).
Here's my method as it stands. What could be improved?
/**
* Does a try catch (Exception) on parsing the given string to the given type
*
* @param c the number type. Valid types are (wrappers included): double, int, float, long.
* @param numString number to check
* @return false if there is an exception, true otherwise
*/
public static boolean isValidNumber(Class c, String numString) {
try {
if (c == double.class || c == Double.class) {
Double.parseDouble(numString);
} else if (c == int.class || c == Integer.class) {
Integer.parseInt(numString);
} else if (c == float.class || c == Float.class) {
Float.parseFloat(numString);
} else if (c == long.class || c == Long.class) {
Long.parseLong(numString);
}
} catch (Exception ex) {
return false;
}
return true;
}