I was making a program where the input must be an integer. I was trying to validate the user input, so I googled up a thing called the try/catch method.
The validation function looks like this:
public static boolean isNumeric(String strNum) {
try
{
int i = Integer.parseInt(strNum);
} catch (NumberFormatException nfe)
{
return true;
}
return false;
}
I was trying to find more information about this line of code catch (NumberFormatException nfe), more precisely the meaning of NumberFormatException nfe this thing.
Question: What exactly is NumberFormatException nfe? And how does it work?
>Solution :
Basically what’s happening here is the following:
- You take the string
strNumand give it toInteger.parseInt(), which is a function that will try to parse thatStringinto anInteger. - If the method
parseInt()doesn’t manage to parse yourstrNum(because it’s not an integer, for example because it isblablaor2.35), then it will throw an exception of typeNumberFormatExceptionthat is namednfe(it’s just a variable name in your code snippet). - If that doesn’t happen, you return
true(meaning yes, yourstrNumis numeric). But if that happens, then you returnfalse(meaning you didn’t manage to parse it as anIntegerand so it’s not numeric).
A couple of things that may help you:
- The thing called try/catch method is called
try/catch/finallyblock. The code you write inside thetrywill be attempted. If an exception is thrown while executing the code, it will be caught in thecatchblock (if declared) so that you can try to make it up. Thefinallyblock (which is optional, and in fact you’re not using it) will be executed no matter what happens, either you execute successfully or not. You should read more about how exceptions are handled in Java and what they are for, I’d suggest you here. - Your function seems to guess whether a string is numeric or not. However, you’re using
Integer.parseInt(). Be aware that the string2.34, which is numeric, will be recognized as not numeric because2.34is aDoubleand not anInteger. So you may want to useDouble.parseDouble()instead, in order to handle the cases where you receive a decimal digit (and it will work also for integer numbers)