Is it a good way to try something useless just to see if a particular exception is thrown by this code ?
I want to do something when the exception is thrown, and nothing otherwise.
try {
new BigDecimal("some string"); // This do nothing because the instance is ignored
} catch (NumberFormatException e) {
return false; // OK, the string wasn't a well-formed decimal
}
return true;
There is too many preconditions to test, and the constructor BigDecimal() is always checking them all, so this seem the simplest method.
Generally, this practice should be avoided. But since there is no utility method
isValidBigDecimal(..), that’s the way to go.As Peter Tillemans noted in the comments, place this code in a utility method called
isValidBigDecimal(..). Thus your code will be agnostic of the way of determining the validity, and you can even later switch to another method.Boris Pavlović suggested an option to check that using a 3rd party library (commons-lang). There’s one more useful method there, which I use whenever I need to verify numbers –
NumberUtils.isNumber(..)