c# - 从异步方法捕获自定义异常

标签 c# .net

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

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)
    {
    }
}

最佳答案

问题是 Wait 抛出一个 AggregateException,而不是您要捕获的异常。

你可以使用这个:

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

关于c# - 从异步方法捕获自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43581990/

相关文章:

.net - 列表框选中项检查

javascript - .NET JavaScript 无法检索文件

c# - 如何在 WPF 中将 ItemsSource 与 ObservableCollection 绑定(bind)

c# - 如何在 Windows Azure 上为 Windows Phone 使用 Microsoft Translator API?

c# - 如何开始,在哪里学习(Farseer)

c# - XML 文档 (30, 14) FormatException : Input string was not in a correct format. 中存在错误?

C# - 列表 Sum() OverflowException : Arithmetic operation resulted in an overflow

.net - 如何检查IEnumerable是否为列表?

c# - HtmlWindow.Error 事件不会因 Javascript 错误而触发

.net - 在不停止服务的情况下更新 dll