Is it OK to try/catch something just to check if an exception was thrown or not?

JavaException

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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(..)

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

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.)

Solution 5 - Java

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.

Solution 6 - Java

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

Solution 7 - Java

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.

Solution 8 - Java

Try / Catch blocks should never be used for logic.

Solution 9 - Java

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:

  • Above code will trap the EXACT data formats accepted by .NET. Anyone who has parsed email addresses will know that there's a lot of variance about what's considered a properly formatted email address structure. This code guarantees to validate email address structures the way that .NET likes, not the way that I think it should be.
  • The exception traps multiple use-cases, not just the correctness of a basic data structure. It will validate multiple users in the CC, BCC and TO fields, which starts to get unwieldy to do with handwritten code.

As others discuss above, this code is best abstracted into a separate utility class rather than mixed in with your main code.

Solution 10 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionClémentView Question on Stackoverflow
Solution 1 - JavaBozhoView Answer on Stackoverflow
Solution 2 - JavaBoris PavlovićView Answer on Stackoverflow
Solution 3 - JavaJon PurdyView Answer on Stackoverflow
Solution 4 - JavaTom Hawtin - tacklineView Answer on Stackoverflow
Solution 5 - JavaoheView Answer on Stackoverflow
Solution 6 - Javabrown.2179View Answer on Stackoverflow
Solution 7 - JavagfidlerView Answer on Stackoverflow
Solution 8 - JavaChris BallanceView Answer on Stackoverflow
Solution 9 - JavaSimon at LabSlice-comView Answer on Stackoverflow
Solution 10 - JavaMr.EddartView Answer on Stackoverflow