VB.NET Exit Statement
In VB.NET, the Exit statement is used to terminate the loop (for, while, do, select case, etc.) or exit the loop and pass control immediately to the next statement of the termination loop. Furthermore, the Exit statement can also be used in the nested loop to stop or terminate the execution of the inner or outer loop at any time, depending on our requirements.
The flow of Exit Statement
Following is the diagrammatical representation of Exit Statement in VB.NET programming language.
Generally, the Exit statement is written along with a condition. If the Exit condition is true inside the loop, it exits from the loop and control transfer to the next statement, followed by the loop. And if the Exit condition fails for the first time, it will not check any statement inside the loop and terminates the program.
We will now see how to use the Exit statement in loops and Select case statements to finish the program's execution in the VB.NET programming language.
Use of Exit statement in While End loop
Example 1: Write a simple program to use the Exit Statement in While End loop.
In the above example, the While End loop is continuously executed, its body until the given condition While (count < 10) is not satisfied. But when the Exit condition (count = 5) falls inside a while loop, the execution of the loop is automatically terminated, and control moves to the next part of the loop statement.
Use of Exit statement in For Next loop
Example 2: Write a program to calculate the sum of 10 numbers, and if a negative number is entered, the For Each loop ends.
The above program accepts a number from the user until it encounters a negative or less than 0 (num < 0). And when there is a negative number, the Exit statement terminates the loop, and the control transfer to the next part of the loop.
Use of Exit statement in Do While loop
Example 3: Write a simple program to use the Exit Statement in Do While Loop.
In the above example, the Do While loop is continuously executed, its body until the given condition While (count < 50) is not satisfied. But when the Exit condition (count = 25) is encountered, the Do While loop is automatically terminated. The control is immediately transferred to the next statement, followed by the loop statements.
Next TopicVB.NET Continue Statement