Search code examples
c#exceptiontry-catchcode-cleanupretry-logic

What is the most efficient way to write this retry logic for a try-catch? C#


I have a C# task that I'd like to re run if a certain exception type is thrown.

This is what I have currently:

bool retry = true;
int numOfRetries = 3;
int tries;

while (retry = true && tries <= numOfRetries)
{
    try
    {
         //Task
         retry = false;
    }
    catch (Exception e)
    {
        if (e.Message.Contains("Unique exception Id like to retry on")
        {
        tries++;
        }
        else
        {
        retry = false; 
        log(e);
        }
    }
}




Solution

  • I suggest using for not while:

    for (int retry = 1; retry <= numOfRetries; ++retry) {
      try {
        DoSomething();
    
        break; // stop looping on success
      }
      catch (Exception e) {
        //TODO: put here condition on e where you should retry
        if (!condition) { // <- no retry
          log(e);
          // you may want to rethrow the exception: throw;
    
          break; // no more retries on unwanted exception
        }  
      }
    }
    

    If you want to catch certain exception types:

    for (int retry = 1; retry <= numOfRetries; ++retry) {
      try {
        DoSomething();
    
        break; // stop looping on success
      }
      catch MyException1:
      catch MyException2:
      catch MyExceptionN:
        ; // catch and do nothing but retry
      catch (Exception e) {
        // no retry
        log(e);
        // you may want to rethrow the exception: throw;
    
        break; // no more retries on unwanted exception
      }
    }