Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch exception in an async method?

Tags:

c#

async-await

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();
}

1 Answers

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();
}
like image 118
Enigmativity Avatar answered Dec 16 '25 00:12

Enigmativity