Should C# event handlers be exception safe?

后端 未结 6 1861
梦如初夏
梦如初夏 2021-02-05 07:14

Assuming that one event has multiple handlers, if any of event handlers throw an exception then the remaining handlers are not executed.

Does this mean that event handle

6条回答
  •  走了就别回头了
    2021-02-05 07:39

    Since invoking an event means that the caller has no knowledge about the callee:

    1. Invoking an event handler should be robust in the face of arbitrary exceptions. Everything up the call stack needs to clean up its own mess correctly, in case something completely unexpected occurs.

    2. Event handlers should really avoid throwing exceptions.

    Things like null reference exceptions are really inexcusable in any code, so obviously we aren't concerned about that.

    Things like file IO exceptions can always happen when writing or reading a file, so I would avoid ever doing IO within an event handler. If it makes sense to do IO in an event handler, then it also makes senst to handle the IO exceptions within the handler too. Don't propogate that back to the caller. Find some way to deal with it.

提交回复
热议问题