c# - 作为聚合异常抛出的自定义异常

标签 c# .net windows-runtime windows-store-apps winrt-async

从 Task.Run(...).Result 引发自定义异常时,catch block 会找到 AggregateException 而不是 CustomException。为什么?

   public MainPage()
    {
        this.InitializeComponent();
        CallAMethod();
    }

    static bool AMethod()
    {
        return Task.Run(() =>
        {
            throw new CustomException();
            return false;
        }).Result;
    }

    static bool CallAMethod()
    {
        try
        {
            return AMethod();

        }
        catch (CustomException e)
        {
            //not caught
            throw;
        }
        catch (Exception ex)
        {
            //caught?
            throw;
        }
    }

这是自定义的异常类

class CustomException : Exception
{

}

最佳答案

from @colinsmith

"当你在一个出错的任务上使用 Task.Wait() 或 Task.Result 时,导致 Task 出错的异常会被传播,但它不会直接抛出......相反,它被包装在一个 AggregateException 对象中,即然后扔了。” ...您可以访问其中的 CustomException

见:Flattening of AggregateExceptions for Processing

关于c# - 作为聚合异常抛出的自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25224202/

相关文章:

c# - 从库中选择图像并压缩 windows phone 8.1

c# - Visual Studio 2019 和 AWS : "not a supported code page" when doing a . NET Core 2.1 项目

c# - 枚举更改事件

c# - 没有死的单声道友好图形库

.net - 使用嵌套验证对复杂模型进行单元测试

c# - Window Phone 8.1 中的 OnNavigatedFrom

c# - 如何从 C# 取消 C++/CX 中的异步操作

c# - 鼠标事件监听器 - 在整个屏幕上?

c# - Gmap.net 缓存如何工作?

c# - 如何将十六进制字符串转换为单精度 float