如何区分 BackgroundWorker.RunWorkerCompleted 事件处理程序中的不同异常类型
我正在用 C# 做一个小爱好项目,这是一种我不太了解的语言,并且偶然发现了以下内容:
假设您有一个使用 BackgroundWorker 实现的异步操作。现在,如果出现异常,将引发事件 RunWorkerCompleted 并且 RunWorkerCompletedEventArgs.Error 将为非空。
以下是处理不同异常类型的规范方法吗? (这里所有的异常类型都是同级 WRT 继承)
if (e.Error != null)
{
FirstKindOfException e1 = e as OneKindOfException;
SecondKindOfException e2 = e as SecondKindOfException;
...
LastKindOfException en = e as LastKindOfException;
if (e1 != null)
{
...
}
else if (e2 != null)
{
...
}
...
else
{
...
}
}
它可以工作,但是......它感觉不对。
I am doing little hobby project in C#, a language I do not know well, and have stumbled upon the following:
Suppose you have an asynchronous operation implemented by using BackgroundWorker. Now if there is an exception, event RunWorkerCompleted will be raised and RunWorkerCompletedEventArgs.Error will be non-null.
Is the following the canonical way then to handle different exception types? (Here all the exception kinds are siblings WRT inheritance)
if (e.Error != null)
{
FirstKindOfException e1 = e as OneKindOfException;
SecondKindOfException e2 = e as SecondKindOfException;
...
LastKindOfException en = e as LastKindOfException;
if (e1 != null)
{
...
}
else if (e2 != null)
{
...
}
...
else
{
...
}
}
It works, but... it doesn't feel right.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
is
来严格限制每个测试的范围:(如果您想要异常中的特殊值,则重新转换)
但说实话,我很少需要处理 许多不同类型的异常。在大多数情况下,只需恢复(补偿)到已知状态并适当报告错误就可以了。一般来说,我更喜欢在开始操作之前测试可能的错误,因此异常确实是异常的。
You could use
is
to keep each test tightly scoped:(then re-cast if you want special values from the exception)
To be honest, though, it is pretty rare that I need to handle lots of different types of exceptions. In most cases, it is fine to simply recover (compensate) to a known state and report the error appropriately. Generally I prefer to test for likely errors before I start the action, so an exception truly is something exceptional.
使用 is 运算符:
或者直接缩短它,因为无论如何您都不知道如何处理这些异常。如果你这样做了,那么你就会在 DoWork() 事件处理程序中捕获它们,在状态消失后尝试处理它们是没有意义的:
Use the is operator:
Or just cut it short since you don't know how to handle these exceptions anyway. If you did then you would have caught them in the DoWork() event handler, there's no point in trying to handle them after the state has evaporated:
使用
是
也许是运营商?Using
is
operator maybe?是的,您可以这样做,但实际上取决于您将如何处理所有这些异常类型。通常这只会显示给用户,因此不需要检查错误的类型。
此外,您还需要记住,异常的类型可能是 AggregateException - 这是从
Task操作返回的 - 所以您需要小心。
Yes, you can do this but really depends what you are going to do with all those exception types. Normally this will only be shown to the user so there is no need to check the type of the error.
Also you need to keep in mind that it is likely the type of the exception could be
AggregateException
- which is return from theTask<T>
operations - so you need to be carefull.