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();
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With