The Visual Basic .NET Programming Language
< Day Day Up > |
Branching statements allow transferring control from one location to another within a method. Exit and Return Statements
The Exit statement allows exiting a particular kind of statement block. The Exit keyword is followed by the kind of block to be exited: Sub , Function , Property , Try , Select , Do , While , or For . If there is no containing block of the type specified, the compiler will give an error. Note that the statement will exit the containing block of the type specified, including any blocks that may be nested within that containing block. For x As Integer = 1 To 10 Dim y As Integer = x While y > 0 y -= 1 If y = 5 Then Exit For End If End While Next x In this example, when the Exit For is reached, execution will leave both the While loop and the For loop. The Return statement returns control from a subroutine or a function, just as an Exit Sub or Exit Function statement does. In a function, however, the Return statement must supply an argument. This argument is returned as the value of the function. For example, the following function adds two numbers together and returns the result. Function Add(ByVal x As Integer, ByVal y As Integer) As Integer Return x + y End Function Goto Statement and Labels
The GoTo statement transfers control to a specified label. A label is a name at the beginning of a line, followed by a colon . Dim x, y As Integer x = FetchValue() If x < 0 Then Goto SkipDivision y = 1 \ x SkipDivision: Return y
It is worth noting that whether a statement is a label or a method invocation may at times be ambiguous because they can look the same. Whenever there is any question, the statement is always assumed to be a label. MsgBox("hello") : MsgBox("world!") ' Two method calls MsgBox: ' label As a matter of style and good programming, use of the GoTo statement should be avoided unless absolutely needed. There are also several situations in which a GoTo statement is not allowed.
The first two restrictions deal with statements that do initialization at the beginning of the block; if the initialization were skipped , statements within the block would not work properly. The rest of the restrictions have to do with the way that the .NET Runtime handles exceptions (the SyncLock statement contains an implicit Try...Catch statement).
|
< Day Day Up > |