Error Handling without Exceptions

后端 未结 7 1182
夕颜
夕颜 2021-02-05 06:02

While searching SO for approaches to error handling related to business rule validation, all I encounter are examples of structured exception handling.

MSDN and many oth

7条回答
  •  长情又很酷
    2021-02-05 06:32

    Exceptions are just that: a way to handle exceptional scenarios, scenarios which should not ordinarily happen in your application. Both examples provided are reasonable examples of how to use exceptions correctly. In both instances they are identifying that an action has been invoked which should not be allowed to take place and is exceptional to the normal flow of the application.

    The misinterpretation is that the second error, the renaming method, is the only mechanism to detect the renaming error. Exceptions should never be used as a mechanism for passing messages to a user interface. In this case, you would have some logic checking the name specified for the rename is valid somewhere in your UI validation. This validation would make it so that the exception would never be part of normal flow.

    Exceptions are there to stop "bad things" happening, they act as last-line-of-defence to your API calls to ensure that errors are stopped and that only legal behaviour can take place. They are programmer-level errors and should only ever indicate one of the following has occured:

    • Something catastrophic and systemic has occurred, such as running out of memory.
    • A programmer has gone and programmed something wrong, be it a bad call to a method or a piece of illegal SQL.

    They are not supposed to be the only line of defence against user error. Users require vastly more feedback and care than an exception will ever offer, and will routinely attempt to do things which are outside of the expected flow of your applications.

提交回复
热议问题