Begin...When Statements

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

Syntax

startClause
  Begin
    [ loopStatements ]
  When { %None | %Done | Else }
    [ afterStatements ]
  ...
endClause

Parts

startClause
Required start clause for any of the loop constructs: Do, For, For Each, or While.
Begin
Required
loopStatements
Optional statements that are repeated by the loop.
When
Required, one or two times
%None
Specifies the start of statements that execute when the loopStatements did not execute.
%Done
Specifies the start of statements that execute when the loopStatements executed to completion.
Else
Specifies the start of statements that execute when either of the %None or %Done conditions are true. If you specify a When Else statement, no more When statements can appear.

afterStatements
Optional
endClause
Required end clause for its respective startClause.

Details

When %Done

If you provide a When %Done clause inside a loop construct, the statements in this block of code are executed only when the loop terminates normally. The statements are executed at most once per loop, almost like any code outside of a loop.

If a loop is terminated prematurely using either the Exit or Return statements, the When %Done clause is skipped entirely, and execution continues where appropriate for the given statement.

When %None

If you provide a When %None clause, the statements in this block of code are executed only when the body of the loop was not executed at all. The following table summarizes the conditions under which this can occur.

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 element In group
When group = #Null or is empty

The When %None clause cannot appear in the post-conditional form of Do...Loop because this form always executes the body of the loop at least once.

When Else

If you use a When Else statement inside a loop construct, it is equivalent to the When %Done and When %None statements combined.

Scope

The scope of identifiers inside these clauses is the same as the loop in which they appear. This means that any variable declared inside them does not exist outside of that loop.

Examples

See also