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

前端 未结 10 637
Happy的楠姐
Happy的楠姐 2020-12-28 13:09

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

相关标签:
10条回答
  • 2020-12-28 13:37

    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

    0 讨论(0)
  • 2020-12-28 13:38

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

    0 讨论(0)
  • 2020-12-28 13:41

    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.

    0 讨论(0)
  • 2020-12-28 13:41

    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.

    0 讨论(0)
提交回复
热议问题