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?
Event handlers are used in graphical user interface (GUI) applications to handle events such as button clicks and menu selections, raised by controls in the user interface. A single event handler can be used to process events raised by multiple controls.
To respond to an event, you define an event handler method in the event receiver. This method must match the signature of the delegate for the event you are handling. In the event handler, you perform the actions that are required when the event is raised, such as collecting user input after the user clicks a button.
About Event Handler Events are declared using delegates. Events are the higher level of Encapsulation over delegate. A delegate that exists in support of an event is called as an event handler. Event handlers are methods in an object that are executed in response to some events occurring in the application.
NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed: A delegate that identifies the method that provides the response to the event. Optionally, a class that holds the event data, if the event provides data.
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.
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
The only two types of exceptions that should come out of events are serious, potentially process-ending ones like System.OutOfMemoryException
or System.DllNotFoundException
, and things that are clearly programming errors, like System.StackOverflowException
or System.InvalidCastException
. Catching and dropping these kinds of exceptions is never a good idea -- let them float up to the top and let the developer decide what to do with them on an application level.
As for the rest... any common or garden-variety exception like System.IO.IOException
should be handled inside your event, and you should have some mechanism for returning such error conditions to the caller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With