Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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) that the class raising the event will have to handle?

Given that such an exception would stop other listeners to that event from being called subsequently, it seems a bit 'antisocial' to allow this to happen, but on the other hand, if there is an exception, what should it do?

question from:https://stackoverflow.com/questions/3114543/should-event-handlers-in-c-sharp-ever-raise-exceptions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
266 views
Welcome To Ask or Share your Answers For Others

1 Answer

Throwing an exception from a event handler is in many ways similar to throwing an exception from a IDisposable.Dispose method (or a C++ destructor). Doing so creates havoc for your caller because you leave them with little option.

  1. Ignore the exception and let it propagate. This breaks their contract to inform all listeners of an event. This is a very real problem if anyone above them on the stack catches the exception.
  2. Catch it call the other handlers and rethrow. But what happens if one of the others throw as well?
  3. Swallow the exception. This is just bad in general. Event sources should have no knowledge of their caller and hence can't know what they're swallowing.
  4. Crash the process because you're toast.

Of all of these #4 is the best option. But this is rarely done and can't be counted on.

I think in your component you really only have a few options

  • You are calling the code which is throwing and are in the best position to handle the exception. If it's not handleable by you then it's unreasonable to expect it to be handled by anyone else. Hence crash the process and be done with it.
  • Don't call the API which throws

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...