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
Yeah this certainly is in contention with the Pragmatic Programmer notion of "Exceptions for exceptional cases" but you recognize what you're doing so there's no problem IMO
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(..)
You have to consider that the construction of the Exception object is expensive in terms of time and resources for the JVM, because it has to construct the strack trace.
So what you propose is an easy but resource-consuming way to solve the problem.
So wether this solution is acceptable or not depends on the use you are going to give to this function, and your efficiency requirements.
Sure, why not. This is what we do to check if an email address specified by the customer is properly formatted:
try
{
MailMessage m = new MailMessage(from, to, subject, body);
return true;
}
catch(SmtpFailedRecipientsException ex)
{
return false;
}
Now, people may argue about the performance or appropriateness of the structure, but they forget the trade-offs in simplicity:
As others discuss above, this code is best abstracted into a separate utility class rather than mixed in with your main code.