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;
}
}
Michael's solution doesn't quite fulfill the requirements, which are to retry a fixed number of times, throwing the last failure.
For this, I would recommend a simple for loop, counting down. If you succeed, exit with break (or, if convenient, return). Otherwise, let the catch check to see if the index is down to 0. If so, rethrow instead of logging or ignoring.
In the example above, a return would have been fine, but I wanted to show the general case.