I have a situation in which a program, communicating over the network, can timeout or otherwise fail to establish a connection through no fault of my application or its user. If and when this happens, an exception is thrown. The solution is obvious; simply try again a couple more times, and if multiple tries don't work then this is really a problem.
I've accomplished this by wrapping the original try-catch in a while loop with a retry counter, producing the following basic pattern:
var retryCount = 0;
while(true)
{
try
{
AttemptToConnect();
break;
}
catch(TimeoutException tex)
{
if(++retryCount < 3) continue;
throw; //or handle error and break/return
}
}
Do any of you see any problems? The biggest smell, prompting me to ask in the first place, is the conditionless loop, which would be infinite except that the "happy path" breaks out of the loop manually, while the terminating error will throw out. This has been called out before as a potential bug generator, if it's ever modified in the future (for instance to catch a second type of exception, or to do something else that could throw an exception).
while (true)
is a code smell. \$\endgroup\$