The Exit statement exits a procedure or block and transfers control immediately to the statement following the procedure call or the block definition.
The basic syntax of the Exit statement looks like as shown below.
Exit { Do | For | Function | Property | Select | Sub | Try | While }
Do loop in which it appears.Exit Do can be used only inside a Do loop.Do loops, Exit Do exits the innermost loop and transfers control to the next higher level of nesting.For loop in which it appears.Next statement.Exit For can be used only inside a For...Next or For Each...Next loop.For loops, Exit For exits the innermost loop and transfers control to the next higher level of nesting.Function procedure in which it appears.Function procedure.Exit Function can only be used inside a Function procedure.Exit Function statement.Return Statement.Property procedure in which it appears.Property procedure, that is, with the statement requesting or setting the property's value.Exit Property can only be used inside a property's Get or Set procedure.Set procedure, the Exit Property statement is equivalent to the Return statement.Select Case block in which it appears.Sub procedure.Exit Sub can be used only inside a Sub procedure.Sub procedure, the Exit Sub statement is equivalent to the Return statement.Try or Catch block in which it appears.Finally block if there is one, or with the statement following the End Try statement otherwise.Exit Try can only be used inside a Try or Catch block, and not inside a Finally block.While loop in which it appears.End While statement.Exit While can only be used inside a While loop.While loops, the Exit While transfers control to the loop that is one nested level above the loop where Exit While occurs.The following example shows that the loop stops using the Exit Do statement when the index variable is greater than 10.
Public Sub Example1()
Dim index As Integer = 0
Do While index <= 100
If index > 10 Then
Exit Do
End If
Console.Write(index.ToString & " ")
index += 1
Loop
End Sub
The following example assigns the return value to the function name Subtract, and then uses Exit Function to return from the function.
Function Subtract(num1 As Integer, num2 As Integer) As Integer
Subtract = num1 - num2
Exit Function
End Function