JavaRush /Courses /C# SELF /Exceptions in Parallel.For and Parallel.ForEach

Exceptions in Parallel.For and Parallel.ForEach

C# SELF
Level 61, Lesson 2
Available

1. How exceptions work in Parallel.For and Parallel.ForEach

In a regular for loop it's simple: if the loop body throws an exception — the loop stops and the exception goes out. In parallel loops it's different. Let's dig in.

All exceptions are collected into one "bag"

When an iteration of a parallel loop (Parallel.For/ForEach) throws an exception, it doesn't immediately fly out — it's packaged. The process continues: other iterations either finish or also throw exceptions. The result: when the parallel loop finishes (or is forced to stop), all thrown exceptions are collected and rethrown as a single AggregateException object.

AggregateException is a "container" that holds a collection of all exceptions that happened during parallel iterations. That's convenient: we always get ALL errors (or at least all that had time to accumulate before the main threads finished).

How this looks in practice

Example: parallel processing that sometimes throws

using System;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 0, 4, 0, 6, 7, 8 };

        try
        {
            Parallel.ForEach(numbers, number =>
            {
                // We intentionally divide by a number that sometimes is zero!
                // This will cause DivideByZeroException
                int result = 100 / number;
                Console.WriteLine($"100 / {number} = {result}");
            });
        }
        catch (AggregateException ex)
        {
            Console.WriteLine("Errors detected in the parallel loop!");

            // Iterate through all exceptions that happened
            foreach (var inner in ex.InnerExceptions)
            {
                Console.WriteLine($"Type: {inner.GetType().Name} — Message: {inner.Message}");
            }
        }
    }
}

What will happen:

  • The main collection contains zeros, and division by 0 is taboo in math (and in C#): DivideByZeroException will occur.
  • The parallel loop starts processing. As soon as a division by zero happens somewhere — the loop won't stop immediately, it will let any iterations that already started keep running.
  • When all threads finish (some with errors, some without), an AggregateException containing all occurred exceptions will be thrown out.

Visualizing the exception handling mechanics

flowchart LR
    A[Thread 1]
    B[Thread 2]
    C[Thread 3]
    D[Thread 4]
    E[Parallel.ForEach]
    F[Exception 1]
    G[Exception 2]
    H[AggregateException]
    subgraph Iterations
      A --> F
      B --> G
      C --> E
      D --> E
      F --> H
      G --> H
      E --> H
    end

The diagram shows: different threads can hit different errors, and in the end they all get "packed" into a single AggregateException.

2. Practical aspects of error handling

What to do with AggregateException?

When you catch AggregateException, there are usually two scenarios:

  • Log or show all errors to the user, to learn from them.
  • Decide which error is critical and which are minor: decide whether to treat the whole operation as failed or ignore some failures.

Typical pattern: handling via Handle

try
{
    Parallel.For(0, 10, i =>
    {
        if (i == 3 || i == 7)
            throw new InvalidOperationException($"Error in iteration {i}");
        Console.WriteLine($"Processed: {i}");
    });
}
catch (AggregateException ex)
{
    ex.Handle(e =>
    {
        if (e is InvalidOperationException)
        {
            Console.WriteLine("Caught error: " + e.Message);
            // true = the error is considered handled
            return true;
        }
        // false = not handled, will be thrown again
        return false;
    });
}

This lets you handle only the errors you consider "normal", and let everything else bubble up so you don't miss critical failures.

Interesting (and dangerous) implementation nuances

When does the loop stop?
When an iteration throws, Parallel.For/ForEach won't start new iterations, but already started ones continue. After all active iterations finish, an AggregateException is thrown. If you have many threads, the "tail" of work will still finish — so you may see multiple errors.

If you don't catch the exception, the app will crash.
If you don't wrap Parallel.For/ForEach in a try-catch, the application will terminate abruptly on the first encountered error after iterations finish — not very friendly to users.

Handling exceptions "inside" the loop.
Sometimes you want individual iterations not to ruin the whole run; you can catch exceptions inside the parallel loop body:

Parallel.ForEach(numbers, number =>
{
    try
    {
        int result = 100 / number;
        Console.WriteLine(result);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error on number {number}: {ex.Message}");
    }
});

This is good if you don't need aggregated exceptions — you handle each failure on the spot (for example, log it). But be careful: if you do this, no AggregateException will appear, and you won't be able to know if everything was OK overall.

If Break() or Stop() is called.
If an iteration calls ParallelLoopState.Break() or ParallelLoopState.Stop(), the loop will try to stop starting new iterations: Break() ends iterations after the current index, while Stop() stops all iterations. However, if an exception occurs at the same time, it will be saved and thrown as an AggregateException after all active iterations finish.

3. Useful nuances

Exceptions in regular loops vs parallel loops

In a regular loop any error causes immediate termination: the exception goes out and everything stops.

In C# parallel loops follow a more compromise approach: work continues for already started tasks, and only after the whole process finishes do all errors "exit" at once. This lets you collect all errors without losing any and make a decision after the loop completes.

4. Typical mistakes when working with exceptions in Parallel.For and Parallel.ForEach

Mistake #1: ignoring AggregateException.
If you don't catch AggregateException, the app will crash after all iterations finish, causing data loss and failures in server or GUI apps.

Mistake #2: using .Wait() without try-catch.
Calling .Wait() for Parallel.For/ForEach without handling AggregateException will lead to an unhandled exception, complicating diagnostics.

Mistake #3: ignoring repeated errors.
Multiple identical errors (e.g., divide by zero) can be thrown because of repeated data. Without analyzing InnerExceptions you might miss the root cause.

Mistake #4: swallowing all exceptions.
Using catch (Exception) { /* empty */ } inside the loop hides errors and causes loss of important info and "ghost" bugs.

Error behavior across different loops

Scenario Regular for/foreach Parallel.For / ForEach
Exception surfacing Immediately After all iterations complete
Error format Single exception AggregateException with a collection
Other iterations Do not run Already started ones finish
Catching errors inside body Yes Yes
Catching errors "outside" Yes Yes, via AggregateException

"Tips" and quick interview questions:

  • What happens if you don't handle AggregateException?
    The application will crash after all iterations complete — regardless of where or when the error happened.
  • Can you know in which exact iteration the error happened?
    Only if you include index or data info in the exception yourself.
  • Can AggregateException be empty?
    No, it's created only when there's at least one inner exception. If there are no errors, it won't be thrown.
  • Are errors handled if caught inside the loop?
    Yes, but then nothing will be thrown outside and AggregateException won't appear.

Now you're ready not just to run loops across multiple threads, but also to smartly handle their parallel "incidents"! And, as always — be careful with multithreading: it loves surprises, especially when nobody's catching them.

2
Task
C# SELF, level 61, lesson 2
Locked
A simple example of using Parallel.For with exception handling
A simple example of using Parallel.For with exception handling
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION