What is the best way to avoid goto?

2019-09-14 21:31发布

问题:

I usually fall into a situation where goto seems to be the best option to my mind. But I have read several times not to use it, and there is always an alternative. Now, I am trying something like this:-

    try{
            //Something that requires internet connectivity;
    }
     catch{
            //Show a message-Internet connectivity lost,and go back to try
    //-->FYI--Ignore "show message", because I am just appending this text to a  
    // textbox. So there won't be a problem of multiple ShowMessage Boxes.
      }

Now, the best option seems to me is to use goto in catch statement, but I am trying to avoid it. try is the first statement in a function, and if I recall that function, I am piling up stacks, so thats not a better option as well. What alternative can I take?

回答1:

Use a while loop with a flag

var tryAgain = true;
while (tryAgain) 
{
    try
    {
        ...
        tryAgain = false;
    }
    catch (...)
    {
        tryAgain = ...
    }
}


回答2:

In this particular case there is nothing wrong with calling the same function recursively and keeping a counter with the number of times you've called it. Something like this (in pseudo code):

public void DoMyInternetThing(int numberOfAttemptsRemaining)
{
    try 
    {
         //do stuff
    }
    catch (ConnectionException) 
    {
        if (numberOfAttemptsRemaining <= 0)
            throw new SomethingBadHappenedException();

        DoMyInternetThing(numberOfAttemptsRemaining - 1);  
    }
}

As with anything recursive you need to ensure you structure it correctly, but this works nicely (I've used it myself) and it avoids your goto (which is not bad in itself, but use of it can lead to spaghetti or badly structured code).



回答3:

If you want to try again, wrap your try-catch in a do-while loop.



标签: c# goto