I have a piece of code like the following:
try
{
Work:
while(true)
{
// Do some work repeatedly...
}
}
catch(Exception)
{
// Exception caught and now I can not continue
// to do my work properly
// I have to reset the status before to continue to do my work
ResetStatus();
// Now I can return to do my work
goto Work;
}
Are there better alternatives compared to using goto
? Or is this a good solution?
It would seem to make more sense to just move the try/catch into the while loop. Then you can just handle the error and the loop will continue as normal without having to route control flow with labels and gotos.
Goto
is very rarely appropriate construct to use. Usage will confuse 99 percent of people who look at your code and even technically correct usage of it will significantly slow down understanding of the code.In most cases refactoring of the code will eliminate need (or desire to use) of
goto
. I.e. in your particular case you can simply movertry/catch
insidewhile(true)
. Making inner code of the iteration into separate function will likely make it even cleaner.Catch and restore the state on each iteration, even though catching outside will work the same, here you are still in the loop and you can decide whether you want to continue or break the loop.
ALSO: Catching an
Exception
is wrong from the beginning (what are you going to do if you catchStackOverflowException
orMemoryLeachException
- EDIT: this is just for example, check documentation to know what you can catch in reality). Catch concrete type of exception which you expect to be thrown.for those very smart in the comments: Why don't catch general exception
It sounds like you really want a loop. I'd write it as:
You might want to use a
do
/while
loop instead; I tend to prefer straightwhile
loops, but it's a personal preference and I can see how it might be more appropriate here.I wouldn't use
goto
though. It tends to make the code harder to follow.Of course if you really want an infinite loop, just put the
try/catch
inside the loop: