0

I tried the following code

 void Main() { List<int> list = new List<int>(new int[]{ 1,2,3,4,5,6,7 }); try { Parallel.ForEach<int>(list, i => PrintEven(i)); } catch(AggregateException ex) { Console.WriteLine( ex); } } private static void PrintEven(int data) { try { if(data%2 != 0) { throw new Exception($" {data} Not Even"); } } catch(Exception ex) { Console.WriteLine(ex.Message); throw; } } 

The "catch" block of PrintEven method does not print all the odd numbers. Meaning that Console.Writeline of the catch block is not always executed.

When I remove "throw" from "catch" block of PrintEven method, then the code prints all the odd numbers.

Questions:

  1. Why throwing an exception from catch block leads to this inconsistency?
  2. How to log some additional info in the catch block and throw an exception?

TIA.

2
  • 1
    Take a look a this question: stackoverflow.com/questions/40149119 Commented Sep 13, 2018 at 8:58
  • This is to be expected. An unhandled exception causes the loop to terminate immediately. Some tasks of your parallel foreach loop may have been executed, some not. Commented Sep 13, 2018 at 9:04

1 Answer 1

0

Actually that code of yours will work just fine, cause parallel will make the process run in multiple thread it will not break main thread and stop the whole thing. The only issue you might find is the order will be randomized. 1. Based on my understanding, you are not supposed throw exception inside catch. Cause, if there is no try catch block to handle this throw you put inside catch then your whole program will broke. 2. The exception class has a lot of property inside, such as CallStack and InnerException which will help you identify the error more in-depth. If you want to log there are quite a lot of nuget package you can use, one famous example is NLog.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.