Exceptions and the TPL

When an exception occurs while using the TPL, it will always get wrapped with an AggregateException before you can catch and handle it. This makes catching specific exceptions quite bothersome as you're basically writing a catch-all block. Bad practices set aside, unwrapping the exception usually meant losing the callstack as well.

This is, of course, something you do not want to happen as the callstack contains valuable information.

try
{
    var task = Task.Run(...)
    task.Wait();
}
catch(AggregateException ex)
{
    ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}

Due to the new async/await system Microsoft introduced in .NET 4.5, they simplified this greatly by introducing the ExceptionDispatchInfo helper.

By using this class, you are able to rethrow a caught exception object without losing the callstack. This allows you to unwrap the AggregateException and rethrow the actual exception. This allows you or the users of your code to catch specific exceptions.

The snippet above is, of course, not a very realistic way to use this helper class, but shows what it does perfectly.

Steven Thuriot

Developer, tinkerer, lifetime student, full time nerd and somewhat of an otaku. Graduated applied computer science. Likes to complain about traffic.

Belgium