5
我試圖捕獲異步方法內引發的自定義異常,但由於某種原因它總是被泛型異常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)
{
}
}
是因爲它抓住了AggregateException? – Stuart
被捕獲的異常是什麼類型?它可能是一個'AggregateException',它可能包含你的'CustomException' –