#160 – A while Loop Can Exit on break, goto, return or throw Statements

In addition to completing normally, when the loop expression evaluates to false, a while loop can exit early.  A loop will exit early if it encounters one of the following statements: break, goto, return or throw.

A break statement causes an early exit of the loop and execution to continue with the first statement after the loop.

            uint numTimes = 0;
            while (numTimes < 100)
                WriteOnBlackboard("I will not eat paste");
                if (ChalkBroke())
                    break;     // Stop writing

The goto statement can transfer control out of a while loop, to a labeled statement.  Its use is rare, since there are generally more elegant ways to transfer control.

The return statement can transfer control out of a loop and return control to the calling method.

The throw statement transfers control out of a loop and throws an exception, indicating that an error condition occurred.