我正在 try 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)
{
}
}
最佳答案
问题是Wait
抛出AggregateException
,而不是您 try catch 的异常。
您可以使用此:
try
{
var t = Task.Run(TestAsync);
t.Wait();
}
catch (AggregateException ex) when (ex.InnerException is CustomException)
{
throw;
}
catch (Exception)
{
//handle exception here
}