从Task.Run(...)抛出自定义异常时。结果,catch块找到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;
}
}
这是自定义的Exception类
class CustomException : Exception
{
}
答案 0 :(得分:3)
来自@colinsmith blogs.msdn.com/b/pfxteam/archive/2011/09/28/... ...“当您对出现故障的任务使用Task.Wait()或Task.Result时,导致任务出错的异常是传播,但它不是直接抛出...而是,它被包装在一个AggregateException对象中,然后抛出它。“ ...你可以访问里面的CustomException ... stackoverflow.com/questions/22872995 / ...