Rethrow exception in for loop

Viewed 28

I want to create a method to retry some code with wait when exception occur. How can I get rid of that last exception?

public static T TryWithWait<T>(Func<T> func, int tries, TimeSpan exceptionSleep)
{
    if (tries < 1)
        throw new Exception("Tries amount cannot be < 1");
    
    for (int i = 0; i < tries; i++)
    {
        try
        {
            return func.Invoke();
        }
        catch
        {
            if (i == (tries - 1))
                throw;
            else
                Thread.Sleep(exceptionSleep);
        }
    }

    throw new Exception("Code wouldn't compile without that");
}
1 Answers

You can use recursivity !

public static T TryWithWait<T>(Func<T> func, int tries, TimeSpan exceptionSleep, Exception innerException = null)
{
    // You must to knows what exception was generated, I put it as InnerException
    if (tries < 1) throw new Exception("Tries amount cannot be < 1", innerException);

    try
    {
        return func.Invoke();
    }
    catch(Exception exception)
    {
        return TryWithWait(func, --tries, exceptionSleep, exception);
    }
}
Related