Skip to content

2.16 — Exceptions in Async Code, AggregateException

← Roadmap · Section: 2. Collections, LINQ and Async Prev: 2.15 async void · Next: 2.17 IAsyncEnumerable

Markers: ⭐ ⚠️ · Confidence: 🔴 · Last reviewed: —


TL;DR

  • An exception in an async Task method is stored inside the returned Task, not thrown immediately. It surfaces when you await.
  • await unwraps it, so you catch the real exception type. .Result does not — you get an AggregateException wrapper instead, and your catch (SqlException) will not match.
  • With Task.WhenAll, awaiting rethrows only the first exception. The others are still on the task.

The concept

In normal synchronous code, an exception travels straight up the call stack until something catches it.

Async breaks that, because the method returns before it finishes (2.11). By the time the failure happens, the caller has already moved on — there is no stack to travel up any more.

So the runtime does something different: it puts the exception in a box — the Task — and hands the box back. The exception sits there quietly until someone opens the box by awaiting it. At that moment it is thrown, on the caller's behalf.

A picture: a parcel with something broken inside. The courier does not tell you at the door. You find out when you open it. If you never open it, you never find out — which is the "unobserved exception" problem later in this note.


How it works

The exception is stored, not thrown

public async Task<int> FailAsync()
{
    await Task.Delay(10);
    throw new InvalidOperationException("boom");
}

var task = FailAsync();          // NO exception here — the task is just faulted
Console.WriteLine("still running");

await task;                      // exception thrown HERE

The task has three possible end states: RanToCompletion, Faulted, or Canceled. Awaiting a faulted task rethrows what is inside it.

await unwraps; .Result does not ⚠️

This is the practical difference that bites people.

// With await — you catch the REAL exception type
try
{
    await GetDataAsync();
}
catch (SqlException ex)          // ✓ matches
{
    _logger.LogError(ex, "Database failed");
}
// With .Result — wrapped in AggregateException
try
{
    var data = GetDataAsync().Result;
}
catch (SqlException ex)          // ✗ NEVER MATCHES
{
    // The thrown type is AggregateException, which WRAPS the SqlException.
    // This catch block is dead code.
}

To handle it you would need:

catch (AggregateException ex) when (ex.InnerException is SqlException sql)
{
    _logger.LogError(sql, "Database failed");
}

Which is a strong argument for never blocking in the first place — see 2.13. await gives you clean, expected exception types.

GetAwaiter().GetResult() does unwrap correctly, unlike .Result — but it still blocks a thread, so it is not a fix.

Task.WhenAll and multiple failures

var t1 = FailAsync("first");
var t2 = FailAsync("second");
var t3 = FailAsync("third");

var all = Task.WhenAll(t1, t2, t3);

try
{
    await all;
}
catch (Exception ex)
{
    // ex is ONLY the first exception. The other two are invisible here.
    _logger.LogError(ex, "Something failed");
}

To see all of them, go to the task itself:

try
{
    await all;
}
catch
{
    foreach (var inner in all.Exception!.InnerExceptions)
        _logger.LogError(inner, "Task failed");
}

all.Exception is always an AggregateException containing every failure. Awaiting only surfaced the first, which is convenient for the common case and misleading when several fail at once.

Where try/catch goes

A try/catch around an await works exactly as you would expect:

public async Task ProcessAsync()
{
    try
    {
        await _db.SaveAsync();       // ✓ caught normally
    }
    catch (DbUpdateException ex)
    {
        _logger.LogError(ex, "Save failed");
    }
}

The state machine restores the try/catch context when it resumes, so exceptions after an await are caught by a catch written before it. That is one of the nicer things the compiler does for you.

But a try/catch around a call without an await does not:

try
{
    var task = ProcessAsync();       // no await — exception goes into the task
}
catch (Exception ex)
{
    // NOT reached. Nothing was thrown here.
}

Cancellation is not a failure

OperationCanceledException is thrown by cancellation and puts the task in the Canceled state, not Faulted. Treat it separately:

try
{
    await DoWorkAsync(ct);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
    _logger.LogInformation("Cancelled");     // routine — not an error
}
catch (Exception ex)
{
    _logger.LogError(ex, "Actually failed");
    throw;
}

See 2.14 for why the when filter matters.

Unobserved exceptions

If a task faults and nobody ever awaits it, the exception is never observed:

_ = SaveAsync();       // fire and forget — if this fails, nobody hears

In .NET Framework this crashed the process when the task was garbage collected. Modern .NET changed the default so it does not — which is safer, but means the failure is now completely silent. Arguably worse for debugging.

You can hook the event to at least log them:

TaskScheduler.UnobservedTaskException += (sender, e) =>
{
    _logger.LogError(e.Exception, "Unobserved task exception");
    e.SetObserved();
};

That is a safety net for diagnostics, not a substitute for awaiting your tasks.


Code

Realistic handling of a set of parallel operations where partial failure is expected:

public async Task<ImportResult> ImportAllAsync(
    IReadOnlyList<string> files,
    CancellationToken ct)
{
    // Each task captures its own outcome rather than throwing outward,
    // so one bad file does not abandon the rest.
    var tasks = files.Select(async file =>
    {
        try
        {
            var count = await ImportFileAsync(file, ct);
            return new FileOutcome(file, count, Error: null);
        }
        catch (OperationCanceledException)
        {
            throw;                              // cancellation must propagate
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "Failed to import {File}", file);
            return new FileOutcome(file, 0, Error: ex.Message);
        }
    });

    var outcomes = await Task.WhenAll(tasks);   // no exception — all handled inside

    return new ImportResult(
        Succeeded: outcomes.Where(o => o.Error is null).ToList(),
        Failed:    outcomes.Where(o => o.Error is not null).ToList());
}

The pattern here — catch inside each task and return a result object — is worth knowing. It avoids WhenAll hiding all but the first exception, and it means one failure does not discard the work that succeeded.

Note that OperationCanceledException is deliberately rethrown. If the whole operation is being cancelled, you do not want to record that as "this file failed".


Interview questions

Q: What happens to an exception thrown inside an async Task method?

It is not thrown to the caller immediately, because the method has usually already returned at its first await. Instead the runtime captures it and stores it on the returned Task, putting that task into the Faulted state. The exception surfaces when someone awaits the task, at which point it is rethrown on the awaiting code. If nobody ever awaits it, the exception is never observed — in modern .NET that no longer crashes the process, but it does mean the failure is completely silent.

Q: Why does catch (SqlException) sometimes not catch a database error in async code?

Because of how you awaited it. await unwraps the stored exception and rethrows the original type, so a typed catch works. But .Result and .Wait() throw an AggregateException that wraps the real one, so a catch (SqlException) never matches and the block is effectively dead code. That is one more reason not to block on tasks — beyond the thread cost, it changes the exception type you have to handle.

Q: If several tasks in a Task.WhenAll fail, what do you get?

Awaiting the combined task rethrows only the first exception, which is easy to mistake for "only one thing went wrong". All of them are recorded on the task itself — task.Exception is an AggregateException whose InnerExceptions collection holds every failure. So if I need to log or report all of them, I keep a reference to the combined task and inspect that in the catch block rather than relying on what await threw.

Q: How would you handle a batch of operations where some are expected to fail?

I would catch inside each individual task and return a result object describing success or failure, rather than letting exceptions escape to WhenAll. That way one bad item does not hide the others behind a single rethrown exception, and it does not discard the work that succeeded. The one exception I would deliberately let propagate is OperationCanceledException, because that means the whole operation is being torn down rather than that one item failed.


Traps ⚠️

  • .Result and .Wait() wrap the exception in AggregateException. Typed catch blocks silently stop matching.
  • Task.WhenAll rethrows only the first exception. Check task.Exception.InnerExceptions for the rest.
  • A try/catch around a call you did not await catches nothing. The exception went into the task.
  • An unobserved faulted task is silent in modern .NET. No crash, no log, nothing.
  • OperationCanceledException is not a fault. Handle it separately or you will log routine cancellations as errors.
  • An exception in async void cannot be caught at all and crashes the process. See 2.15.
  • throw inside a catch in an async method preserves the stack correctly, but throw ex still resets it, exactly as in sync code. See 1.20.


Sources