Should a business rule violation throw an exception?

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

Should a business rule violation throw an exception?

14条回答
  •  臣服心动
    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.

提交回复
热议问题