Q:

When there is an exception in a loop, what is the best way to attempt the action 3 (finite) times before moving on to the next iteration?

I have a loop which does an action(PDF Generation) in each iteration
If in one iteration there is an exception (in generating the PDF,) I want to try again for 3 times; before I move on to the next iteration/record.
What is the best way to do this?
Thanks.

A:

One simple approach is to use a do/while nested loop inside the main loop, and count retries there, like this:
foreach (var item in allReportingItems) {
    var retries = 0;
    var reportIsGenerated = false;
    do {
         reportIsGenerated = TryGeneratingReport(item);
         retries++;
        // The loop will end when the report gets generated
        // or when the retries count would be exhausted
    } while (!reportIsGenerated && retries < 3);
    if (!reportIsGenerated) {
        Concole.Error.WriteLine(
            "Unable to generate report for {0} after 3 retries", item
        );
    }
}

