从 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
{
}
最佳答案
"当你在一个出错的任务上使用 Task.Wait() 或 Task.Result 时,导致 Task 出错的异常会被传播,但它不会直接抛出......相反,它被包装在一个 AggregateException 对象中,即然后扔了。” ...您可以访问其中的 CustomException
关于c# - 作为聚合异常抛出的自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25224202/