HomeSearch

VB.NET Exit Statements

Understand Exit statements, like Exit While and Exit Sub. Exit breaks out of code blocks.

Exit. The Exit keyword breaks out of loops and Subs. It is followed by the name of the block we want to leave. This means that Exit While will stop the While-loop from iterating. And control flow will resume at the end of the loop.While, Do While

Exit While. In this first example we use Exit in a While-loop. This program contains four Console.WriteLine statements. These help us locate the control flow as it proceeds through the statements.

A, B: Statement A is reached when the program begins. B is reached only once because the loop body is only entered once.

C, D: C is not reached because the Exit While statement is first encountered. Statement D is reached after the Exit While statement is hit.

VB.NET program that uses Exit While 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 Output A B D

Exit Sub. Next 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 that can help increase program symmetry.

So: For example, if a While-loop contains an Exit While, the Exit Sub is more symmetric to this.

VB.NET program that uses Exit Sub 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 Output A B

Discussion. In the C# language, a break statement exits from an enclosing loop. In this context, break is the same as Exit. But in VB.NET Exit can be used instead of Return. And Exit must specify the block type to escape from.

The Exit For statement does the same thing as the Exit While statement but acts upon a For-loop construct. These different statements are useful when nested—we can even Exit from a loop that is not immediately enclosing the statement.For Each, For

Exit Do: As with other loop Exit statements, Exit Do breaks out of an enclosing Do loop.

Summary. In VB.NET, we use Exit statements to stop procedural units from executing. This is simpler and easier to understand than attempting to set loop variables, such as i, to an out-of-range value to cause loop termination.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.