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
If you dislike having a method like this one, try using BigDecimalValidator from Apache Commons Validator. In case of an invalid input String
it returns null
.
There's nothing wrong with doing this; after all, proponents of a certain other language are fond of saying "it's easier to apologise than to ask permission", that is, it's easier to wait for something to fail and deal with it than it is to avoid failure altogether. In this case, since there is no alternative, absolutely go for it.
A comment on kriss' answer: I don't see a "superb memory leak" here. There is no reference to the created BigDecimal. As soon as this method completes, and we go out of scope, the object is eligible for garbage collection.
Memory leaks occur when we hold references we no longer need so the object can't be garbage collected.
Try / Catch blocks should never be used for logic.
There's two known method to "check" preconditions.
LBYL : Look before you leap
This coding style explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the EAFP approach and is characterized by the presence of many if statements.
EAFP : Easier to ask for forgiveness than permission.
This common coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
EAFP is always a good idea for language that have duck typing.
It clearly depends on what you want to do... If you are not sure of the kind of the object to manipulate, use EAFP.
Performance might not be great and the syntax verbose, but the code is very precise about what it does. There is no duplication between check and use, which is always a big concern.
(Note, this particular sort of conversion to and from strings is really for debugging and internal configuration. It doesn't handle locales and other human-oriented consideration. Use in file formats and wire protocols introduces a strong dependency to the representation used by the class.)