首页 > 解决方案 > 抛出错误的异常

问题描述

我有一个作为进度表的表单,我执行的任务如下:

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从进度表单中抛出的内容按原样到达调用方法?

标签: c#winforms

解决方案


这对我有用:

try
{
    await Task.Run(() =>
    {
        //Run task here...
    });
}
catch (AggregateException ex)
{
    foreach (Exception inner in ex.InnerExceptions)
    {
         if (inner is MyCustomException)
         {
             //todo smt..
             throw inner;
         }
    }
}

推荐阅读