Should a business rule violation throw an exception?

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

Should a business rule violation throw an exception?

14条回答
  •  深忆病人
    2021-02-04 04:58

    As an alternative view to most of the answers...

    It can be useful to throw exceptions from the business logic, particularly if they are cuased by a failure in validation. If you are expecting an object and you get a null, it suggests that some problem has evaded detection in the user interface (or other interface). It may be completely valid to throw exceptions at this point. Indeed, you may decide to place this type of validation in the business logic when there are multiple interfaces.

    Throwing exceptions in some languages / frameworks (I am thinking .NET) can be costly but this should not immediately worry you. It does mean that, at the name suggests, they are used for exceptional circumstances and not as part of the standard flow of a program. You certainly shouldn't throw an exception just to exit a method. You should also consider a graceful recovery where possible that may not include throwing an exception.

    So, summing up... It depends...

提交回复
热议问题