Skip to content
Back to Curriculum
FUNDAMENTALS

Control Flow & Errors

Solidity supports standard control flow (`if`, `else`, `for`, `while`). Error handling is done via `require`, `revert`, and `assert`. Understanding how to revert transactions effectively is key to gas efficiency and security.

Syntax Structure

Example.sol
Loading...

Key Components

  • Boilerplate structure required by the Solc compiler.
  • Placement of state variables versus functions.

Practical Implementation

Using custom errors to save gas compared to string requires.

Practical.sol
Loading...

Core Concepts

require

Checks conditions. If false, reverts changes and refunds remaining gas. Used for inputs.

assert

Checks invariants. If false, consumes ALL gas (panic). Used for internal errors.

revert

Imperatively stops execution. Can return custom error data.

Mental Model

The Emergency Stop Button

In normal coding, an error might crash the app. In Solidity, an error (`revert`) is a **Time Machine**. It undoes *everything* that happened in the current transaction as if it never occurred, preserving the blockchain's integrity.

Under the Hood

`revert` compiles to the `REVERT` opcode, which halts execution and returns a data payload. `assert` compiles to `INVALID` (0xFE), consuming all gas. Loops (`JUMP`) must be bounded, or they will hit the Block Gas Limit.

JUMPIREVERTINVALID

Gas Analysis

Reverting early saves gas. Custom errors save gas over strings.

  • • Always validate inputs at the very top of the function.
  • • Use Custom Errors (`error MyError()`) instead of strings for cheaper deployment and execution.

Security Risks

Unhandled exceptions can leave contracts in broken states (rare due to atomicity, but logic matters).

  • ! DoS with Block Gas Limit: Iterating over an array that can grow indefinitely will eventually make the function uncallable.

Common Use Cases

Validating user balance before transfer.
Looping through arrays (carefully).
Returning detailed error messages to the frontend.

Interactive Visualization

See exactly how the EVM handles this code in memory, storage, and the stack.

Interactive Simulation
0 / 0
Loading...
Type Solidity code (v0.8.26) and click Run. Compiler loads on first use (~2MB).

Click Run to execute the simulation

Then use the step controls to navigate