skip to content

In C#, when two of the tasks passed to Task.WhenAll throw, why does a catch around await Task.WhenAll see only one exception, and how do you get them all?

level: seniorimportance: must knowfreq 60%

answer

  1. the combined task keeps every failure
  2. await unwraps instead of wrapping
  3. keep a reference to the WhenAll task
  4. InnerExceptions, not InnerException

basics

~20 s

The task returned by Task.WhenAll faults with an AggregateException holding every failure, but await rethrows only the first of them, with its original type. Keep a reference to the combined task and read its Exception.InnerExceptions to see them all.

solid answer

~40 s

`Task.WhenAll` returns a task that, once every input has finished, ends `Faulted` if any input faulted, and its `Exception` property is an `AggregateException` with each input's exceptions. `await` does not throw that wrapper: the awaiter rethrows the **first** stored exception through `ExceptionDispatchInfo`, so `catch (InvalidOperationException)` works and the stack trace is preserved, but the other failures are not in what you caught. To report all of them, store the combined task (`Task all = Task.WhenAll(a, b, c);`), `await all` inside `try`, and in the `catch` read `all.Exception!.InnerExceptions`, or check each input's `IsFaulted` and `Exception`. Which failure counts as first is not a documented contract, so do not branch on it. If nothing faulted but something was canceled, the combined task ends `Canceled` and `await` throws an `OperationCanceledException`.

code

csharp · 21 lines
csharp
Task profile = FailAsync("profile down", 200);
Task orders = FailAsync("orders down", 50);
Task recs = Task.Delay(100);
Task all = Task.WhenAll(profile, orders, recs);
try
{
    await all;
}
catch (Exception ex)
{
    Console.WriteLine($"caught: {ex.GetType().Name}: {ex.Message}");
}
Console.WriteLine($"status: {all.Status}");
foreach (Exception inner in all.Exception!.InnerExceptions)
    Console.WriteLine($"inner: {inner.Message}");

static async Task FailAsync(string message, int ms)
{
    await Task.Delay(ms);
    throw new InvalidOperationException(message);
}

go deeper

for a junior

Remember that Task.WhenAll's task keeps every failure, but a catch around the await sees one exception with its original type.

for a middle

Explain how the awaiter rethrows the first stored exception through ExceptionDispatchInfo, and how to read all failures from the combined task's Exception.InnerExceptions.

for a senior

Make sure logging and error reports keep every failure when several services fail at once, and know that WhenAll waits for all inputs and ranks faults above cancellations.

for a principal

Decide whether a group of calls should fail fast with cancellation or collect every outcome, and make that choice explicit in shared helpers rather than leaving it to each caller.

## What Task.WhenAll's task holds `Task.WhenAll` takes a set of tasks and returns one task that completes when **all** of them have completed. Its documented final state follows three rules, read from the runtime source's remarks: 1. If any supplied task **faulted**, the combined task ends `Faulted`, and its exceptions are the **aggregation** of the unwrapped exceptions from every faulted input. 2. If none faulted but at least one was **canceled**, the combined task ends `Canceled`. 3. Otherwise it ends `RanToCompletion`, and the generic overload's result is an array of every result. So nothing is lost at this level: the combined task's `Exception` property is an `AggregateException` whose `InnerExceptions` collection contains every failure. Note the plural: `InnerException` (singular, inherited from `Exception`) shows only one of them. ## What await does with it `await` asks the task's awaiter for the result. When the task is faulted, the awaiter's own source comment says it throws "its first exception, even if it contained more than one". It throws that exception through `ExceptionDispatchInfo`, which keeps the original stack trace and the original type. That design is deliberate: - `catch (HttpRequestException)` works after an `await`, instead of every caller having to unwrap an `AggregateException`; - code that awaits one task and code that awaits a combination look the same; - the cost is that the **second and later failures are not in the exception you caught**. Microsoft's guide to task exception handling says the same thing from the other side: `GetAwaiter().GetResult()` throws one exception, while `Task.Exception` stores an `AggregateException` with all of them. Blocking with `.Wait()` or `.Result` throws the `AggregateException` itself, with every inner exception, but blocking on async code brings deadlock risk of its own. ## Which failure is "first" The documentation does not promise an order, and the implementation differs between overloads. Running .NET 10 shows it: | Overload | Order of `InnerExceptions` | Exception `await` rethrows | |---|---|---| | `Task.WhenAll(params Task[])` | the order the failures arrived | the earliest failure | | `Task.WhenAll<TResult>(params Task<TResult>[])` | the order the tasks were passed | the first faulted argument | Treat this as an observation, not a contract. Code that decides what to do based on which exception `await` happened to surface is fragile. ## Getting every failure Keep a reference to the combined task: ```csharp Task all = Task.WhenAll(profile, orders, recs); try { await all; } catch (Exception) { foreach (Exception e in all.Exception!.InnerExceptions) logger.LogError(e, "dashboard load failed"); } ``` Alternatives with the same effect: - check each input after the `catch`: `profile.IsFaulted ? profile.Exception : null`, and so on; - call `AggregateException.Flatten()` when inputs may themselves have faulted with nested aggregates; - for partial results, read `Result` only from inputs whose `IsCompletedSuccessfully` is `true`. `Task.WhenAll` also marks each input's exceptions as **observed** when it collects them, so a faulted input you passed to it will not later raise `TaskScheduler.UnobservedTaskException`. The combined task's own exception is observed when you await it. ## Choosing what callers see A shared helper that wraps `Task.WhenAll` has to decide what its own callers receive: - **rethrow the first failure**, the default `await` behaviour, which keeps `catch` blocks simple but hides the rest; - **throw the combined task's `AggregateException`** with `throw all.Exception!;`, which hands every failure up but forces callers to unwrap it; - **return per-task outcomes** (a result or an exception per input), so partial success is data rather than an exception. Whichever it picks, it should log every inner exception at the point where all of them are still in hand. ## Two behaviours people get wrong - **No fail-fast.** The combined task does not complete when the first input faults; it waits for every input. Siblings keep running, and stopping them early needs a cancellation token that you cancel on the first failure. - **Faults outrank cancellations.** With one faulted and one canceled input, the combined task is `Faulted`, and `await` throws the fault. Only when nothing faulted does `await` throw an `OperationCanceledException`, usually a `TaskCanceledException`. ## Interview angle The question checks whether a candidate knows the difference between the task's stored state and what `await` surfaces, and whether their logging and error reporting would silently drop the second outage when two services fail together.

  • Does the task from `Task.WhenAll` complete as soon as the first input faults?
    No. It completes only when every supplied task has completed, so a fast failure still waits for the slowest sibling, and the siblings keep running. To stop early, pass the inputs a `CancellationToken` and cancel it when the first failure is seen, then await the combined task.
  • Why does `catch (AggregateException)` around `await Task.WhenAll(...)` usually never run?
    Because `await` rethrows the first inner exception with its own type, not the wrapper. The catch matches only if an input itself threw an `AggregateException`. Catch the specific types, or catch `Exception` and then read the combined task's `Exception.InnerExceptions`.
  • One input faults and another is canceled. What does `await Task.WhenAll(a, b)` throw?
    The fault. A faulted input makes the combined task `Faulted`, whatever else was canceled, and `await` rethrows the first stored exception. Only when no input faulted and at least one was canceled does the combined task end `Canceled`, and `await` then throws an `OperationCanceledException`.

  • await Task.WhenAll throws an AggregateException containing every failure.
  • Once await rethrows the first exception, the other failures are gone for good.
  • Task.WhenAll completes as soon as one of its tasks faults.
  • The exception await surfaces is always the one that failed earliest.
  • A canceled input outranks a faulted one in Task.WhenAll's final status.