Begin...When Statements

Executes a particular block of code depending on how a loop exits.

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 executed to completion.
Else
Specifies the start of statements that execute when either of the %NONE or %DONE conditions are true. If you use Else, you cannot use %NONE or %DONE.
after_statements
Optional
end_clause
Necessary end clause for its respective start_clause.

Instructions

When identifier

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

When %DONE

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

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

When %NONE

If you use a When %NONE clause, 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 The When %NONE clause in the constructs Do...Loop While and Do...Loop Until because they execute their statements a minimum of one time.

When Else

If you use a When Else statement in a loop construct, it is equivalent to the When %DONE and When %NONE statements put together.

Scope

The scope of variables in these clauses is the same as variables in the usual loop construct. This means that any variable declared in them does not exist 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