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 sounds like you really want a loop. I'd write it as:
bool successful = false;
while (!successful)
{
try
{
while(true)
{
// I hope you have a break in here somewhere...
}
successful = true;
}
catch (...)
{
...
}
}
You might want to use a do
/while
loop instead; I tend to prefer straight while
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:
while (true)
{
try
{
...
}
catch (Exception)
{
...
}
}
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 mover try/catch
inside while(true)
. Making inner code of the iteration into separate function will likely make it even cleaner.
while(true)
{
try
{
// 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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With