Skip to main content

Catch multiple async exceptions as AggregateException example.

private async static Task CatchMultipleExceptions()
{
    Task task1 = Task.Run(() => { throw new Exception("Message 1"); });
    Task task2 = Task.Run(() => { throw new Exception("Message 2"); });

    try
    {
        await Task.WhenAll(task1, task2).WithAggregatedExceptions();
    }
    catch (AggregateException e)
    {
        Console.WriteLine("Caught {0} exceptions: {1}",
            e.InnerExceptions.Count, string.Join(", ",
                e.InnerExceptions.Select(x => x.Message)));
    }
}