Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to write retry logic without goto [duplicate]

Tags:

c#

.net

goto

Is there a better way to write this code without using goto? It seems awkward, but I can't think of a better way. I need to be able to perform one retry attempt, but I don't want to duplicate any code.

public void Write(string body)
{
    bool retry = false;
RetryPoint:
    try
    {
        m_Outputfile.Write(body);
        m_Outputfile.Flush();
    }
    catch (Exception)
    {
        if( retry )
            throw; 
        // try to re-open the file...
        m_Outputfile = new StreamWriter(m_Filepath, true);
        retry = true;
        goto RetryPoint;
    }
}
like image 963
CluelessCoder Avatar asked Nov 10 '10 20:11

CluelessCoder


People also ask

How do you write retry logic in Java?

1. Simple for-loop with try-catch. A simple solution to implement retry logic in Java is to write your code inside a for loop that executes the specified number of times (the maximum retry value).

What is a retry logic?

Retry logic is implemented whenever there is a failing operation. Implement retry logic only where the full context of a failing operation. It's important to log all connectivity failures that cause a retry so that underlying problems with the application, services, or resources can be identified.

How do you retry a connection in python?

You can specify a function to filter out exception you want to ignore or the one you want to use to retry. retry will call the function passed as retry_on_exception with the exception raised as first argument. It's up to the function to then return a boolean indicating if a retry should be performed or not.


1 Answers

Here is the basic logic that I would use instead of a goto statement:

bool succeeded = false;
int tries = 2;

do
{
    try
    {
        m_Outputfile = new StreamWriter(m_Filepath, true);
        m_Outputfile.Write(body); 
        m_Outputfile.Flush(); 
        succeeded = true;
    }
    catch(Exception)
    {
        tries--;
    }
}
while (!succeeded && tries > 0);

I just added # of tries logic, even though the original question didn't have any.

like image 76
Michael S. Scherotter Avatar answered Sep 24 '22 22:09

Michael S. Scherotter