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?
-
4msdn.microsoft.com/en-us/library/dd460695(v=vs.110).aspxVivek Nuna– Vivek Nuna2016-10-20 08:24:09 +00:00Commented Oct 20, 2016 at 8:24
-
This MSDN Article should answer your question. It's pretty simple.Saket Kumar– Saket Kumar2016-10-20 08:33:56 +00:00Commented Oct 20, 2016 at 8:33
-
Some exceptions you should try to avoid altogether. For example, using TryParse instead of Parse.Robert Harvey– Robert Harvey2020-12-15 16:25:03 +00:00Commented Dec 15, 2020 at 16:25
2 Answers
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.
Comments
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