Should a business rule violation throw an exception?

后端 未结 14 632
误落风尘
误落风尘 2021-02-04 04:18

Should a business rule violation throw an exception?

相关标签:
14条回答
  • 2021-02-04 05:10

    Do you mean, for example, that a value is supposed to be in the range 0-99 but somehow ended up being 105?

    If it's coming from the user it's a matter of validation. Whether it is handled using exceptions or not depends on the idioms of your language.

    If it's coming from your data store then yes, it seems reasonable to throw an exception. It means you have bad data and you need to figure out how it got there and prevent it from happening again.

    0 讨论(0)
  • 2021-02-04 05:13

    First, a couple of quotes from chapter 18 of Applied Microsoft .NET Framework Programming (page 402) by Jeffrey Richter:

    "Another common misconception is that an 'exception' identifies an 'error'."

    "An exception is the violation of a programmatic interface's implicit assumptions."

    If I'm inferring correctly from your question that a business rule violation would be data that falls outside a certain range (for example), this is an error that you could handle with a conditional as @ahockley suggested. Based on the definition of an exception from Richter, the appropriate use of an exception would be if your code wasn't able to retrieve a business rule from whatever repository you're using. Being able to retrieve a business rule would be a reasonable implicit assumption for that interface to have, so an exception should be thrown if this assumption was violated.

    One good example of Richter's first quote (exception != error) is the ThreadAbortException. If you call Response.Redirect(url) (in ASP.NET), a ThreadAbortException is thrown even though the redirect succeeds. Why? The implicit assumption of ASP.NET page execution is that a page will execute completely. Response.Redirect(url) violates this assumption, hence the exception.

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