从异步方法中捕获自定义异常

时间:2017-04-24 07:17:43

标签: c# .net

我试图捕获异步方法中抛出的自定义异常但由于某种原因它总是被通用异常catch块捕获。请参阅下面的示例代码

class Program
{
    static void Main(string[] args)
    {
        try
        {
            var t = Task.Run(TestAsync);
            t.Wait();
        }
        catch(CustomException)
        {
            throw;
        }
        catch (Exception)
        {
            //handle exception here
        }
    }

    static async Task TestAsync()
    {
        throw new CustomException("custom error message");
    }
}

class CustomException : Exception
{
    public CustomException()
    {
    }

    public CustomException(string message) : base(message)
    {
    }

    public CustomException(string message, Exception innerException) : base(message, innerException)
    {
    }

    protected CustomException(SerializationInfo info, StreamingContext context) : base(info, context)
    {
    }
}

1 个答案:

答案 0 :(得分:10)

问题在于Wait会抛出AggregateException,而不是您要捕获的异常。

您可以使用:

try
{
    var t = Task.Run(TestAsync);
    t.Wait();
}
catch (AggregateException ex) when (ex.InnerException is CustomException)
{
    throw;
}
catch (Exception)
{
    //handle exception here
}