In VB.NET programs, the Exit keyword breaks out of loops and Subs. It is followed by the name of the block we want to leave.
In a function, Exit While will stop the While
-loop from iterating. And control flow will resume at the end of the loop.
We use Exit in a While
-loop. This program contains 4 Console.WriteLine
statements. These help us locate the control flow as it proceeds through the statements.
Module Module1 Sub Main() Console.WriteLine("A") Dim i As Integer = 10 While True Console.WriteLine("B") If i = 10 Then Exit While End If Console.WriteLine("C") End While Console.WriteLine("D") End Sub End ModuleA B D
Sub
In this next example, we see the Exit Sub
statement. This statement breaks out of the entire Sub
. This is the same as a Return statement.
Sub
is an alternative syntax to Return. If a While
-loop contains an Exit While, the Exit Sub
is more symmetric to this.Module Module1 Sub Main() Console.WriteLine("A") Dim i As Integer = 10 While True Console.WriteLine("B") If i = 10 Then Exit Sub End If Console.WriteLine("C") End While Console.WriteLine("D") End Sub End ModuleA B
In the C# language, a break
statement exits from an enclosing loop. Break is the same as Exit. But in VB.NET Exit can be used instead of Return.
For
-loop construct.In VB.NET, we use Exit statements to stop procedural units from executing. This is simpler than attempting to set loop variables to an out-of-range value to cause loop termination.