Chapter 10Lesson 03170–230 min

IF/ELSE, FOR, WHILE, TRY/EXCEPT, BREAK, CONTINUE, and Control Flow: Configuration, Design Patterns, and Trade-Offs

Choose deliberately among native control flow, helper keywords, templates, bounded polling, error matching modes, expression styles, and Python extraction based on readability, failure transparency, portability, and CI behavior.

Design choicesTrade-offsPollingError matchingExpression safety

Learning objectives

  • Choose native control flow versus user-keyword or Python-library extraction based on complexity and intent.
  • Distinguish FOR loops from data templates and WHILE loops from domain-specific polling helpers.
  • Select exact, START, GLOB, or REGEXP error matching intentionally and explain the failure-hiding risk of broad EXCEPT.
  • Choose ${var} replacement or $var expression access based on value type and trust boundary.
  • Relate control-flow choices to output size, parallel execution cost, CI diagnosis, and security.

Current compatibility baseline. Verified 2026-08-31: Robot Framework 7.4.2 is the current stable release; 7.5b1 is a pre-release and is not required in this chapter. Native IF/ELSE arrived in Robot Framework 4.0; WHILE, TRY/EXCEPT, BREAK, CONTINUE, and inline IF are available in modern Robot Framework 5.0+ syntax. Robot Framework 7.4.2 gives WHILE a default 10,000-iteration limit; production examples here set a smaller explicit limit.

1. Design principle: control flow should clarify intent, not merely reduce lines

Native syntax is concise, but fewer lines are not automatically more maintainable. The key question is whether a reviewer can predict which branch runs, what failure is recoverable, how long repetition can last, and which state is mutated. If those answers require mentally executing a mini-program, the abstraction is too low for the test layer.

2. Native syntax versus helper keyword versus Python

Need Prefer Reason
One visible conditional business rule Native IF in test/domain keyword Intent remains obvious
Repeated orchestration with a reusable contract User keyword Centralizes limit, trace, and recovery
Algorithm, parser, complex policy, graph traversal Python library Better unit testing and language tooling
Known finite data cases FOR or template depending intent FOR is orchestration; templates are data-driven test design
Expected keyword failure mapping Narrow TRY/EXCEPT Preserves unmatched failures

3. FOR versus data templates

A FOR loop means one test/task performs repeated steps. If the third iteration fails, the overall item fails as one result and preceding iterations are evidence inside that same result. A test template (Chapter 11) generates semantically separate data-driven cases or iterations according to template rules. Choose based on result identity, not just source compactness.

4. WHILE versus a bounded polling keyword

WHILE is useful when each iteration has meaningful orchestration. For a common readiness condition, a named polling keyword is often clearer because it owns the deadline, interval, evidence, and failure message. Avoid using an arbitrary Robot loop to imitate a domain library’s condition-specific wait when that library can observe readiness directly.

Wait For Synthetic State
    [Arguments]    ${expected}    ${max_attempts}=6
    VAR    ${attempt}    ${0}
    WHILE    ${attempt} < ${max_attempts}    limit=${max_attempts}
        ${attempt}=    Evaluate    $attempt + 1
        ${actual}=     Read Synthetic State    ${attempt}
        Log    attempt=${attempt}; actual=${actual}
        IF    $actual == $expected
            RETURN    ${actual}
        END
    END
    Fail    State did not become '${expected}' in ${max_attempts} attempts

5. Match errors as narrowly as the contract allows

EXCEPT style Use when Risk
Exact (default) Failure message is stable and specific Lowest accidental catch surface
type=START Stable prefix + variable suffix May catch unrelated errors sharing prefix
type=GLOB Controlled variable fragments Wildcards can become too broad
type=REGEXP Structured messages truly require regex Harder review; easy accidental overmatch
No message Boundary intentionally maps any ordinary failure Highest risk of hiding assertions/defects

6. ${var} replacement versus $var access

Condition input Preferred form Why
Integer/boolean with simple representation ${count} > 0 can be fine Replacement remains valid Python
Arbitrary string $name == "ready" No manual quoting of value
List/dict/object $items or len($items) > 0 Uses actual object instead of repr text
Untrusted external text $value as data only Do not splice data into executable expression text

7. Inline IF is for one-statement branches, not compressed programs

Inline IF can make small choices readable, especially with RETURN, BREAK, or CONTINUE. Once several ELSE IF branches or long arguments appear, use normal block syntax. Compression increases review cost and makes failure traces harder to scan.

IF    $item is None    CONTINUE
IF    $state == "ready"    RETURN    ${state}

8. Legacy-compatible BuiltIn controls are not the modern design default

Run Keyword If remains supported, but the User Guide generally recommends native IF/ELSE. Likewise Exit For Loop and Continue For Loop still work for compatibility, but native BREAK/CONTINUE are recommended and the older loop-control keywords are planned for eventual deprecation/removal. Do not introduce the wrapper style into a new 7.4.2 course unless dynamic keyword dispatch is the real requirement.

9. Runtime and output trade-offs

Large loops expand output.xml and log.html. Repeated polling also consumes external capacity. Optimize only after measurement: count iterations, measure elapsed time, identify external latency, and preserve enough loop detail for diagnosis. --removekeywords/--flattenkeywords can reduce result size later, but they should not be used to hide evidence while designing a flaky loop.

10. Parallelism and shared state

Control flow does not create isolation. A FOR loop that mutates one shared file or account is still unsafe if multiple tests/workers use the same resource later with Pabot. Use unique identities and narrow state ownership from earlier chapters; a branch or loop only chooses operations on that state.

11. Worked decision scenario

Requirement Choice Rationale
Check three fixed synthetic candidates FOR Finite orchestration inside one verification
Wait up to five reads for one expected state Named keyword with WHILE limit=5 Central bounded polling contract
Map only “transient:*” to recovered TRY + GLOB prefix Unmatched permanent errors fail
Parse a 40-line policy with nested conditions Python library Algorithmic complexity belongs outside Robot test syntax
Condition on arbitrary label text $label Avoid string-representation quoting hazards

12. Knowledge check

Why might a template be better than FOR for a set of independent input/output examples?

When is an EXCEPT without a message defensible?

What is wrong with relying on a 10,000-iteration WHILE default?

Does extracting logic to Python make Robot Framework less useful?

13. Summary and next step

Control-flow design is a placement decision. Use native syntax for small readable orchestration, user keywords for reusable bounded contracts, templates for data-driven result identity, and Python for algorithmic complexity. Lesson 4 applies these choices to realistic failure modes and diagnosis.

Next lesson

IF/ELSE, FOR, WHILE, TRY/EXCEPT, BREAK, CONTINUE, and Control Flow: Diagnostics, Failure Modes, and Production Practices

Continue with IF/ELSE, FOR, WHILE, TRY/EXCEPT, BREAK, CONTINUE, and Control Flow: Diagnostics, Failure Modes, and Production Practices. It builds directly on the state, evidence, and operating assumptions established here, so carry those constraints forward rather than treating the next page as an isolated topic.

Further reading

Keep the academy open

Support free, practical DevOps education.

Every lesson is designed to remain readable in a browser, downloadable from GitHub, and usable without a paid learning platform. Contributions help expand and maintain the curriculum.

Ethereum / ERC-20
0x716c4Ab160C4B66F31a28AE2448BfF68fc3a2ef0 Send only Ethereum/ERC-20 compatible assets to this address.