Should event handlers in C# ever raise exceptions?

前端 未结 5 745
攒了一身酷
攒了一身酷 2020-12-14 14:59

As a general rule, are there ever any circumstances in which it\'s acceptable for a method responsible for listening to an event to throw an exception (or allow to be thrown

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-14 15:29

    In an ideal world, event handlers shouldn't raise exceptions. Raising an exception in an event handler tends to lead to very difficult to handle situations, and unexpected behavior. As you mentioned- this blocks subsequent event handlers from seeing the event, and the exception propagates into the event producer's code since it raised the event.

    Ideally, event handlers should be fast (if they're long running, they should try to schedule the work in a separate thread) and as close to error free as possible.

提交回复
热议问题