Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use goto statement? [closed]

Tags:

c#

goto

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?

like image 577
Nick Avatar asked Nov 07 '12 17:11

Nick


2 Answers

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)
    {
        ...
    }
}
like image 133
Jon Skeet Avatar answered Oct 02 '22 07:10

Jon Skeet


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();
  }
}
like image 39
Alexei Levenkov Avatar answered Oct 02 '22 06:10

Alexei Levenkov