1

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.

Gadam
  • 2,674
  • 8
  • 37
  • 56
  • Side note: [think twice before using exceptions](http://stackoverflow.com/q/1744070/912144) – Shahbaz Oct 24 '13 at 15:28
  • Ordinarily, creating a PDF file is a determinate operation (if no user interaction is involved) that will produce the same result every time. It is likely that trying again will waste time and accomplish nothing. If there is user interaction: users don't like software that they can't control. If the software always tries three times, even when the user wants to cancel, they won't use the software, or will complain about it to anyone and everyone. – James Waldby - jwpat7 Oct 24 '13 at 17:32

2 Answers2

1

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
        );
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

You can basically just have a for-loop counting the number of tries.

In pseudo-code:

for each action
  success = false
  for tries = 0; tries < 3 && !success; tries++
    success = doAction(action)

Or, with exceptions:

for each action
  success = false
  for tries = 0; tries < 3 && !success; tries++
    try
      doAction(action)
      success = true
    catch exception
      // do nothing
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
  • marking #dasblinkenlight as answer because that fit better into my existing code, given the way my try catches are set up. Great answer, thanks. – Gadam Oct 24 '13 at 15:56