应在C#中的事件处理程序曾经引发异常? [英] Should event handlers in C# ever raise exceptions?
问题描述
作为一般规则,是有过在它是可以接受的方法,负责监听事件抛出一个异常(或允许抛出)阶级引发事件将要处理的情况?
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?
推荐答案
从事件处理程序抛出异常是类似于抛出多种方式从 IDisposable.Dispose
方法(或C ++析构函数)异常。这样做对你的来电者创建浩劫,因为你让他们几乎没有选择。
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.
- 忽略异常,让它传播。这打破了他们的合同,告知事件的所有侦听器。这是一个很现实的问题,如果有人在他们之上堆栈上捕捉异常。
- 抓住它拨打对方的处理程序和重新抛出。但是,如果其他人之一奉送会发生什么?
- 燕子例外。这仅仅是坏一般。事件源应该没有其呼叫者的知识,因此不能知道他们吞咽什么。
- 因为你是敬酒崩溃的过程。
- 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.
- Catch it call the other handlers and rethrow. But what happens if one of the others throw as well?
- 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.
- Crash the process because you're toast.
所有这些#4是最好的选择。但这很少完成,不能指望。
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
- 您正在调用哪一个是投掷并在处理异常的最佳位置的代码。如果不是被你可加工那么它是不合理的期望它被其他人处理。因此崩溃的过程,并用它来完成。
- 请不要调用会抛出
这篇关于应在C#中的事件处理程序曾经引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!