1. Introduction
Imagine you start a bunch of async tasks at once — parsing websites, checking prices on marketplaces, or computing large arrays. Everything kicks off, but a few tasks fail: a server doesn't respond somewhere, some data is bad somewhere else. In synchronous code you'd see one exception, but in async code you can have multiple errors. That's where the AggregateException comes in — it collects all errors into one "container".
What is AggregateException?
AggregateException is a special exception type in .NET that aggregates errors from parallel/async operations: Task.WhenAll, Parallel.For, TPL, etc. When two or more tasks finish with errors, they get "packed" into a single AggregateException object.
Where does AggregateException appear?
The most common scenario is waiting for multiple tasks via Task.WhenAll:
// Example — run several tasks in parallel, some of which throw exceptions
var tasks = new List<Task>
{
Task.Run(() => throw new InvalidOperationException("Oshibka #1")),
Task.Run(() => throw new ArgumentException("Oshibka #2")),
Task.Run(() => { Console.WriteLine("Task 3 completed successfully!"); })
};
try
{
await Task.WhenAll(tasks); // With await AggregateException is unwrapped here
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.GetType().Name} - {ex.Message}");
}
But there's a nuance: with await the AggregateException is unwrapped and the first inner exception is thrown "as is". If you don't use await and instead access Result or call Wait(), you'll get the actual AggregateException.
2. What does AggregateException look like?
This exception has an InnerExceptions collection — all nested errors:
try
{
Task task = Task.WhenAll(tasks);
task.Wait(); // Here you'll get AggregateException if there were errors
}
catch (AggregateException aggEx)
{
Console.WriteLine($"Total errors: {aggEx.InnerExceptions.Count}");
foreach (var e in aggEx.InnerExceptions)
{
Console.WriteLine($"Type: {e.GetType().Name}, Message: {e.Message}");
}
}
Sample output:
Total errors: 2
Type: InvalidOperationException, Message: Oshibka #1
Type: ArgumentException, Message: Oshibka #2
How AggregateException is formed
+--------------------------+
| We start several |
| Tasks |
+-----+---------+----------+
| |
v v
Task1 Task2 ... TaskN
| |
| (fails with an error)
|-------------------+
| v
| Exception2
v
Exception1
|
v
+---------------------------------+
| Task.WhenAll or Parallel.For |
| (collects all |
| exceptions) |
+---------------------------------+
|
v
AggregateException
(InnerExceptions: all errors)
Why you don't see AggregateException with await?
With await .NET "unwraps" the AggregateException and throws the first inner exception (InnerExceptions[0]).
// A single task that throws InvalidOperationException
try
{
await Task.Run(() => throw new InvalidOperationException("Oshibka!"));
}
catch (Exception ex)
{
// Here ex is InvalidOperationException, not AggregateException
Console.WriteLine(ex.GetType().Name); // InvalidOperationException
}
If you want access to all errors — use Wait() or Result (but remember about blocking the thread).
3. Catching and handling all exceptions
Let's connect theory to practice. Suppose several tasks process user data and you need to log all failures.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MyApp
{
class Program
{
static async Task Main(string[] args)
{
var tasks = new List<Task>
{
Task.Run(() => throw new InvalidOperationException("Ne ta operatsiya!")),
Task.Run(() => throw new DivideByZeroException("Delenie na nol!")),
Task.Run(() => Console.WriteLine("Third task succeeded"))
};
try
{
// Await tasks asynchronously — we get the first inner exception
Task allTasks = Task.WhenAll(tasks);
await allTasks; // on await AggregateException is unwrapped
}
catch (Exception ex)
{
// With await we'll see only the first inner exception
Console.WriteLine($"First error: {ex.GetType().Name} - {ex.Message}");
// If it's an AggregateException — you can iterate all of them
if (ex is AggregateException aggEx)
{
foreach (var inner in aggEx.InnerExceptions)
{
Console.WriteLine($"Error from list: {inner.GetType().Name} - {inner.Message}");
}
}
}
// Now catch all errors synchronously
try
{
var allTasks = Task.WhenAll(tasks);
allTasks.Wait(); // blocks the thread — don't do this in UI!
}
catch (AggregateException aggEx)
{
foreach (var e in aggEx.InnerExceptions)
{
Console.WriteLine($"[Wait] Error: {e.GetType().Name} — {e.Message}");
}
}
}
}
}
With await inside a try/catch you'll see only the first error. With Wait() you'll get the classic AggregateException with all nested errors.
4. Bulk error handling
In real apps you often need to handle many errors differently. For example, you're sending emails to all users and some sends fail:
var sendTasks = emailList.Select(email => Task.Run(() => SendEmail(email))).ToList();
try
{
Task.WaitAll(sendTasks.ToArray());
}
catch (AggregateException aggEx)
{
foreach (var ex in aggEx.InnerExceptions)
{
if (ex is SmtpException)
Console.WriteLine("Email send error: " + ex.Message);
else
Console.WriteLine("Unknown error: " + ex.Message);
}
}
This way you log each failure and can take individual measures.
5. Useful nuances
Reasons for this behavior
.NET assumes convenience: in a UI usually the first error is enough (when using await). But on a server or systems where handling all failures matters, AggregateException is indispensable.
Pattern: Flatten — unwind the error list
The Flatten() method turns nested AggregateExceptions into a flat list:
catch (AggregateException aggEx)
{
foreach (var ex in aggEx.Flatten().InnerExceptions)
{
Console.WriteLine($"Flattened error: {ex.GetType().Name} — {ex.Message}");
}
}
How Task behaves with different wait strategies
| How we wait for the task | Which exception we catch |
|---|---|
|
The first inner error |
|
Always AggregateException |
|
Always AggregateException |
| Individual await | The exception thrown by the task, or the first inner error if the task completed with AggregateException |
Important to remember
- AggregateException is useful in any scenario where many errors can happen at the same time.
- For await it's convenient to catch the first error; for synchronous waiting — iterate all InnerExceptions.
- Use Flatten() and Handle() for neat handling.
- Don't mix synchronous and asynchronous waiting in UI: you'll get freezes and deadlocks.
7. Common mistakes when handling AggregateException
Myth: await Task.WhenAll always throws AggregateException. Actually — no, the exception is unwrapped and you'll see the first inner one.
Accessing Result or calling Wait() blocks the thread until tasks complete. In UI this will cause the interface to hang.
If you want to handle some errors "silently", use Handle():
catch (AggregateException aggEx)
{
aggEx.Handle(ex =>
{
if (ex is InvalidOperationException)
{
// We handled this error, don't rethrow it
return true;
}
return false; // Other exceptions will be rethrown
});
}
GO TO FULL VERSION