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:
- Why throwing an exception from catch block leads to this inconsistency?
- How to log some additional info in the catch block and throw an exception?
TIA.