Sobes.tech
Middle+

Will the catch block logic for compensation work correctly when using await Task.WhenAll? What exception will be thrown?

sobes.tech AI

Answer from AI

When using await Task.WhenAll(...), if one or more tasks complete with an exception, an AggregateException will be thrown in the catch block. This exception contains all the exceptions that occurred in the individual tasks.

The catch block logic works correctly, but it is important to remember that you need to handle specifically the AggregateException to access all internal errors.

Example of handling:

try
{
    await Task.WhenAll(tasks);
}
catch (AggregateException ex)
{
    foreach (var inner in ex.InnerExceptions)
    {
        Console.WriteLine(inner.Message);
    }
}

In .NET Core and newer, when using await, AggregateException is automatically unwrapped, and you can catch specific exceptions directly. However, if you catch Exception, you can get an AggregateException.