I have seen two styles for checking whether a variable is a valid integer in Java. One by doing an Integer.parseInt
and catching any resulting exception. Another one is by using Pattern.
Which of the following is better approach?
String countStr;
int count;
try {
count = Integer.parseInt(countStr);
} catch (Exception e) {
//return as the variable is not a proper integer.
return;
}
or
String integerRegex = "([0-9]{0,9})";
if (countStr.isEmpty() || !Pattern.matches(integerRegex, countStr)) {
//return as the variable is not a proper integer.
return;
}
My question here is, is doing an Integer.parseInt()
and catching an exception for validation a standard way to validate an int
? I admit that my regex is not perfect. But is there any built-in methods available in Java for validation of int? Actually isn't it better to do some validation instead of simply catching the exception?