I'm a C# programmer. I try to avoid
goto
at all costs, and generally I try to avoid
throw
ing exceptions for the purpose of controlling the flow of execution. I've always been of the opinion that exceptions are for exceptional situations and indicate errors rather than expected conditions.
I suggest encapsulating this sort of code in its own method. You can just return from the method early if one of the
goto
conditions is met.
public void SomeMethod()
{
MethodThatReturnsEarlyIfCertainConditionsAreMet();
}
private void MethodThatReturnsEarlyIfCertainConditionsAreMet()
{
Random random = new Random();
int i = random.Next(10);
if (i < 10) return;
DoOtherWork();
i = random.Next(10);
if (i < 5) return;
DoMoreOtherWork();
}
While I like the idea of all methods having only one return, in practice I don't feel that it's worth it, especially for situations like this.
I don't know how this sort of thing would behave in C++, but I know in C#, the CLR would handle cleanup of your locals when the method returns, which ultimately includes calling destructors if they are used, though Microsoft's recommendation in .NET languages is to implement
IDisposable
when you have unmanaged resources to clean up.