beginner
+175 XP

Control Flow - Making Decisions

Master if expressions, loops, and error handling with assert and abort

Lesson Syllabus

If Expressions
🔀

If as an Expression

In Move, 'if' is an expression that returns a value! Both branches must return the same type. This is different from many languages where if is just a statement.

📋

If-Else Syntax Rules

When using if to return a value: 1) Condition in parentheses 2) Both branches in braces 3) Both must return SAME type 4) Else is required

🌳

Nested If for Complex Logic

You can nest if expressions inside each other for complex decision trees. Each level can return different values based on multiple conditions.

Loops & Iteration
🔁

While Loops

While loops repeat code as long as a condition is true. Great for counting, searching, or repeating until a goal is reached.

🔄

Infinite Loops & Break

Use 'loop' for infinite loops. Use 'break' to exit when you're done. Useful when you don't know in advance how many iterations you need.

⏭️

Continue Statement

Use 'continue' to skip the rest of the current iteration and jump to the next one. Perfect for skipping unwanted values.

⚠️

Loop Safety in Smart Contracts

WARNING: Infinite loops can lock up blockchain transactions! Always ensure loops terminate. Smart contract platforms limit execution time (gas). Design loops carefully!

Error Handling

Assert for Safety Checks

Use assert! to check preconditions - things that must be true for your function to work correctly. If the check fails, the program aborts with your error code.

🛑

Abort for Explicit Failures

Use 'abort' to explicitly fail with an error code. Unlike assert, you use abort in response to runtime conditions or invalid state, not just preconditions.

🎯

Assert vs Abort: When to Use Each

ASSERT for programmer errors (preconditions): amount > 0, caller is admin. ABORT for user/state errors (expected failures): insufficient balance, item not found.

📝

Error Codes Best Practices

Use meaningful error codes (constants). Document what each code means. This helps debugging when things fail. Start from 0 or use descriptive names.