I am learning async and await. The following "catch" does not catch the exception thrown in DoTask. Assuming DoTask is a third party method that I can't change, how do I fix it so that the catch clause does catch the exception?
private static async Task DoTask()
{
await Task.Delay(10000);
throw new Exception("Exception!");
}
public static void Main(string[] args)
{
try
{
Task.Run(async () => await DoTask());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("End");
Console.ReadKey();
}
CodePudding user response:
How about this simplification:
public static async Task Main(string[] args)
{
try
{
await DoTask();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("End");
Console.ReadKey();
}
CodePudding user response:
Catching AggregateException
will be possible if you use async/await
- so the reason you don't catch it is not awaiting the Task.Run inside main - it just escapes the try
clause immediately.
CodePudding user response:
I worked out - I need to wait for the task to finish. After I added the "Task.WaitAll(task);", it caught the exception.
private static async Task DoTask()
{
await Task.Delay(10000);
throw new Exception("Exception!");
}
public static void Main(string[] args)
{
try
{
Task task = DoTask();
Task.WaitAll(task);
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException.Message);
}
Console.WriteLine("End");
Console.ReadKey();
}