Home
VB.NET
Exit Statements
Updated 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 20, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen