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();
}
}
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.
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 catch StackOverflowException
or MemoryLeachException
- 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.
while(true)
{
try
{
// Do some work repeatedly...
}
catch(FileNotFoundException) //or anything else which you REALLY expect.
{
// I have to reset the status before to continue to do my work
ResetStatus();
//decide here if this is till OK to continue loop. Otherwise break.
}
}
for those very smart in the comments: Why don't catch general exception