Continue looping after throwing exception

Let's say I have a code like this:

try { for (int i = 0; i < 10; i++) { if (i == 2 || i == 4) { throw new Exception("Test " + i); } } } catch (Exception ex) { errorLog.AppendLine(ex.Message); } 

Now it’s obvious that execution will stop at i==2 , but I want it to complete the entire iteration, so that there are two entries in errorLog (for i==2 and i==4 ) So, is it possible to continue the iteration, even an exception is thrown ?

+6
source share
2 answers

Just change the catch scope inside the loop, not outside it:

 for (int i = 0; i < 10; i++) { try { if (i == 2 || i == 4) { throw new Exception("Test " + i); } } catch (Exception ex) { errorLog.AppendLine(ex.Message); } } 
+38
source

Why do you generally throw an exception? You can immediately write to the log:

 for (int i = 0; i < 10; i++) { if (i == 2 || i == 4) { errorLog.AppendLine(ex.Message); continue; } } 
+6
source

Source: https://habr.com/ru/post/946101/


All Articles