Begin...When Statements

Execute a different block of code given what the loop does.

Syntax

start_clause
  Begin [ identifier_list ]
    [ loop_statements ]
  When { identifier | %NONE | %DONE | Else }
    [ after_statements ]
  ...
end_clause

Parts

start_clause
Necessary start clause for any of the loop constructs: Do, For, For Each, or While.
Begin
Necessary
identifier_list
Optional, one or more identifiers with a comma between each.
loop_statements
Optional statements that are repeated by the loop.
When
Necessary, one or more times
identifier
Necessary for each identifier in identifier_list. Specifies the start of statements that execute after “Exit identifier”.
%NONE
Specifies the start of statements that execute when the loop_statements did not execute.
%DONE
Specifies the start of statements that execute when the loop_statements completed.
Else
Specifies the start of statements that execute when one of the conditions, %NONE or %DONE, are true. If you use Else, you cannot use %NONE or %DONE.
after_statements
Optional executable statements.
end_clause
Necessary end clause for its related start_clause.

Instructions

When identifier

If you use When identifier in a loop construct, then the statements in this block of code execute because of Exit identifier.

When %DONE

If you use When %DONE in a loop construct, then the statements in this block of code execute only when the loop stops as usual. The statements execute at most one time for each loop, almost like any code outside of a loop.

If a loop stops because of Exit or Return statements, then When %DONE never executes. Thus execution continues as usual for the given statement.

When %NONE

If you use When %NONE, then the statements in this block of code execute only when the body of the loop never executed at all. A table that summarizes the conditions in which this can occur follows.

Loop constructLoop body not executed
While condition
When condition is initially false
Do While condition
When condition is initially false
Do Until condition
When condition is initially true
For c = start To end [ Step step ]
When start > end for a positive step. Or start < end for a negative step
For Each item In group
When group is #Null or is empty

Note: You cannot use When %NONE in Do…Loop While and Do…Loop Until because they execute their statements a minimum of one time.

When Else

If you use When Else in a loop, it is the same as When %DONE and When %NONE put together.

Scope

The scope of variables in these blocks is the same as variables in the usual loop construct. Thus you cannot use variables declared in them outside of the loop.

Examples

When identifier

For Each name$ In names$()
  Begin found
    If name$ = match$ Then Exit found
  When found
    PrintLine "Match found."
  When %DONE
    PrintLine "No matches found."
End For

See also