debugjavaMajor
Is this a good isNaN method?
Viewed 0 times
thisisnanmethodgood
Problem
public boolean isNaN(String string){
@SuppressWarnings("unused")
BigDecimal bg = null;
try{
bg = new BigDecimal(string);
}catch(Exception e){
return true;
}
return false;
}There is no native
isNaN method for BigDecimal. The thing I don't like about this method is the suppressed warning. I never use the variable but only the constructor to see if it doesn't throw an exception. If it does, I return the corresponding boolean.What do you think?
Solution
You said :
I never use the variable but only the constructor to see if it doesn't throw an exception
I would ask you, then why did you declare a variable at all ? You could have done :
When you don't need a variable, don't declare it.
You should not catch
I never use the variable but only the constructor to see if it doesn't throw an exception
I would ask you, then why did you declare a variable at all ? You could have done :
public boolean isNaN(final String string) {
try {
new BigDecimal(string);
} catch (final Exception e) {
return true;
}
return false;
}When you don't need a variable, don't declare it.
You should not catch
Exception because it's too generic. What do you really want ? The constructor throw NumberFormatException if the argument is not valid, the better option would be to catch that one instead.Code Snippets
public boolean isNaN(final String string) {
try {
new BigDecimal(string);
} catch (final Exception e) {
return true;
}
return false;
}Context
StackExchange Code Review Q#65021, answer score: 26
Revisions (0)
No revisions yet.