c# - 抛出错误的异常
问题描述
我有一个作为进度表的表单,我执行的任务如下:
protected override void OnShown(object sender, EventArgs e)
{
try
{
await Task.Run(() =>
{
//Run task here...
});
}
catch (OperationCanceledException oex)
{ }
catch
{
throw;
}
finally
{
Close();
}
}
调用方法是:
try
{
using (var progress = new ProgressForm(() =>
{
//The task to run async...
}))
{
progress.ShowDialog();
};
}
catch (MyCustomException cex)
{ }
catch (Exception ex)
{ }
AMyCustomException
被任务抛出,所以进度表只是重新抛出它。然而,回到调用方法,这个异常并没有被捕获(在catch (Exception ex)
块中捕获),因为它从进度表单中得到的异常是TargetInvocationException
,并且它InnerException
的类型是MyCustomException
。
为什么会发生这种情况,有没有办法确保MyCustomException
从进度表单中抛出的内容按原样到达调用方法?
解决方案
这对我有用:
try
{
await Task.Run(() =>
{
//Run task here...
});
}
catch (AggregateException ex)
{
foreach (Exception inner in ex.InnerExceptions)
{
if (inner is MyCustomException)
{
//todo smt..
throw inner;
}
}
}
推荐阅读
- php - 刀片视图显示关系数据
- android - 模拟器或实际设备上的 Ionic Live Reload 不起作用
- vba - 检查 DT Picker 结果,将工作表复制到新工作簿中
- jekyll - jekyll博客的baseurl,url应该是什么?
- python - BeautifulSoup-Python:如何抓取尚未加载的数据?
- postgresql - 为什么我从我的 Postgres 数据库中获取 iso 8601 日期?
- user-interface - 如何通过用户移动控制点来计算 3D 旋转矩阵
- node.js - 使用节点触发 Twilio Rest API。
- php - 如何减小 Google PHP 库的大小?
- python - 如何在 Networkx 中查找具有 Python 字符串匹配函数的节点?