Error Handling without Exceptions

后端 未结 7 1165
夕颜
夕颜 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:28

    I assume that you are creating your own business rules validation engine, since you haven't mentioned the one you're using.

    I would use exceptions, but I would not throw them. You will obviously need to be accumulating the state of the evaluation somewhere - to record the fact that a particular rule failed, I would store an Exception instance describing the failure. This is because:

    1. Exceptions are serializable
    2. Exceptions always have a Message property that is human-readable, and can have additional properties to record details of the exception in machine-readable form.
    3. Some of the business rules failures may in fact have been signaled by exceptions - a FormatException, for instance. You could catch that exception and add it to the list.

    In fact, this month's MSDN Magazine has an article that mentions the new AggregateException class in .NET 4.0, which is meant to be a collection of exceptions that occurred in a particular context.


    Since you're using Windows Forms, you should use the built-in mechanisms for validation: the Validating event and the ErrorProvider component.

提交回复
热议问题