BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Parallel and Asynchronous
.NET 4.0+

Exceptions and Parallel Loops

The sixth part of the Parallel Programming in .NET tutorial is the last instalment that examines the parallel loops. This article discusses how exceptions are thrown by code within a parallel loop and how they can be handled.

Accessing the Exception Details

Once you have caught an AggregateException you can examine each of the contained exceptions by reading the InnerExceptions property. This returns a read-only collection that may be addressed by index or enumerated.

The sample code below demonstrates the use of the InnerExceptions property by introducing two changes. First, the division has been modified to give the possibility that two exceptions will be thrown, rather than one. These occur when the loop control value is -10 or zero. The second change is that the catch block now loops through the InnerExceptions property of the AggregateException and outputs all of the error messages.

try
{
    Parallel.For(-10, 10, i =>
    {
        Console.WriteLine("100/{0}={1}", i, 100 / (i % 10));
    });
}
catch (AggregateException ex)
{
    foreach (Exception inner in ex.InnerExceptions)
    {
        Console.WriteLine(inner.Message);
    }
}

/* OUTPUT

100/-5=-20
100/5=20
100/6=16
100/7=14
100/8=12
100/9=11
100/-8=-12
100/-7=-14
100/-6=-16
100/-2=-50
100/-1=-100
100/1=100
100/-9=-11
100/2=50
100/3=33
100/4=25
100/-4=-25
100/-3=-33
Attempted to divide by zero.
Attempted to divide by zero.

*/
7 September 2011