Home
VB.NET
Exit Statements
This page was last reviewed on Jun 20, 2023.
Dot Net Perls
Exit. 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.
Keyword notes. In a function, Exit While will stop the While-loop from iterating. And control flow will resume at the end of the loop.
Do While
Exit While. 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.
Console.WriteLine
Info Statement A is reached when the program begins. B is reached only once because the loop body is only entered once.
And C is not reached because the Exit While statement is first encountered. Statement D is reached after the Exit While statement is hit.
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 Module
A B D
Exit 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.
Also Exit 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 Module
A B
Discussion. 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.
Also The Exit For statement does the same thing as the Exit While statement but acts upon a For-loop construct.
Tip These different statements are useful when nested. We can even Exit from a loop that is not immediately enclosing the statement.
For
Detail As with other loop Exit statements, Exit Do breaks out of an enclosing Do loop.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 20, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.