27

I have a Parallel.ForEach loop in my code and I am wondering how to handle exceptions. Should I catch and handle(e.g write to log) exceptions inside the loop or should I catch aggregate exception outside - encapsulate the loop in try/catch?

3

2 Answers 2

32

Should I catch and handle exceptions inside the loop or should I catch aggregate exception outside

Those two are not functionally equivalent. Both can be done, with different effects.

The fundamental question is: when one or more iterations suffer an exception, do you want the remaining items to be processed or not?

If yes, then handle them inside the loop, possibly storing them like in the MSDN example.
If not then just put a try/catch around the Parallel loop itself.

Sign up to request clarification or add additional context in comments.

Comments

3

When you add your own exception-handling logic to parallel loops, each exception should be catched and saved to a list(Use Concurrent Queue), because each loop will create different exception. So after the loop exists we can wrap all exceptions from the list in a System.AggregateException and throw it.

MSDN Exaplanation and code example here -> How to: Handle Exceptions in Parallel Loops

2 Comments

A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.
“each exception should be catched and saved to a list”. Alternatively, depending on the requirements, instead of collecting exceptions to a list, we can log them and continue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.