This question already has an answer here:
- Cleanest way to write retry logic? 25 answers
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;
}
}
Here is the basic logic that I would use instead of a goto statement:
I just added # of tries logic, even though the original question didn't have any.
@Michael's answer (with a correctly implemented out catch block) is probably the easiest to use in your case, and is the simplest. But in the interest of presenting alternatives, here is a version that factors the "retry" flow control into a separate method:
You could, of course, improve this with things like retry counts, better error propagation, and so on.
with a boolean
What if you put it in a loop? Something similar to this, maybe.
Try something like the following: