How to: Transfer Control Out of a Control Structure (Visual Basic)
You can use the Exit Statement (Visual Basic) to exit directly from a control structure. Exit immediately transfers execution to the statement following the last statement of the control structure. The syntax of the Exit statement specifies which type of control structure you are transferring out of. The following versions of the Exit statement are possible:
Exit statements can appear as many times as needed within a control structure that supports them. Exit is useful when a control structure has done everything it needs to do and does not need to run any more statements.
Control Structures that Do Not Support Exit. You cannot use the Exit statement to transfer out of an If, Using, or With block. To achieve the same result, you can put a statement label on the block's End statement and transfer to it using a GoTo statement. For more information on statement labels, see How to: Label Statements (Visual Basic).
If an Exit statement is encountered within nested control structures, control passes to the statement following the end of the innermost structure of the kind specified in the Exit statement. The following example illustrates this.
Public Sub invertElements(ByRef a(,) As Double) For i As Integer = 0 To UBound(a, 1) For j As Integer = 0 To UBound(a, 2) If a(i, j) = 0 Then ' Cannot complete this row; resume outer loop. Exit For Else a(i, j) = 1.0 / a(i, j) End If Next j ' Control comes here directly from the Exit For statement. Next i End Sub
In the preceding example, the Exit For statement is located in the inner For loop, so it passes control to the statement following that loop and continues with the outer For loop.