Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 47 ยท Language Basics

Control Flow, require, revert and Custom Errors

Learn Solidity control flow and error handling: loops and their gas cost, require, assert, revert, custom errors, try/catch and panic codes.

Solidity's if, for and while look like JavaScript or C, so you will pick up the syntax in minutes. The part that is new is what happens when something goes wrong. On Ethereum a failed call does not just return an error code that you might forget to check. It reverts: every state change made during that call is undone, as if it never ran. This all-or-nothing behavior is what makes contracts safe to reason about, and it is the main tool you have for enforcing rules.

This lesson covers control flow, the three ways to stop with an error (require, revert, assert), custom errors, try/catch, and the cost of loops.

Four ways to say "stop"

require Check an input or a condition.
revert Stop now, with a reason or custom error.
assert Check something that must never be false.
panic The compiler's built-in checks, like overflow.

All of them undo the state changes of the call.

1 / 2

if, loops and conditions

The usual statements exist: if, else, for, while, do { } while, break, continue, return and the ternary cond ? a : b. One difference from JavaScript: a condition must be a real bool. There is no "truthy" conversion, so if (balance) does not compile, and you write if (balance != 0).

SOLIDITY
function sumTo(uint256 n) public pure returns (uint256 total) {
    for (uint256 i = 1; i <= n; i++) {
        total += i;
    }
}

Loops cost gas

Each loop iteration spends gas, and the block has a gas limit. A loop whose length grows with user data, such as looping over every holder in an array, will eventually need more gas than a block allows, and then no one can call that function at all. This is a denial of service risk. Good habits:

  • Avoid unbounded loops over arrays that users can grow.
  • Let each user do their own work in one call (pull instead of push), rather than looping over everyone.
  • When a loop is unavoidable, process a bounded chunk per call, with a start index and a count.
  • Read storage into a local variable before the loop, because every storage read costs far more than a local variable access.

The Gas Costs and Optimization lesson measures this properly.

require, revert and assert

require(condition, "message") is the standard guard for inputs, state and permissions. If the condition is false it reverts, optionally with a message:

SOLIDITY
function withdraw(uint256 amount) external {
    require(amount > 0, "amount is zero");
    require(balances[msg.sender] >= amount, "insufficient balance");
    balances[msg.sender] -= amount;
    // ...send the ether
}

revert stops unconditionally and is handy inside if branches with more complex logic: if (x) { revert("bad"); }.

assert(condition) is for invariants, things that should be impossible, such as a total that must always equal the sum of the parts. A failing assert produces a Panic (code 0x01), and in practice it signals a bug in your contract rather than a bad input. Use require for anything a caller could cause and assert only for internal sanity checks.

The reason string in require is stored in the contract's code and returned as the error data, which makes every string cost deployment size and gas. That is why custom errors exist.

Custom errors

Since Solidity 0.8.4 you can define your own errors with parameters and revert with them:

SOLIDITY
error InsufficientBalance(uint256 available, uint256 requested);
error NotOwner();

function withdraw(uint256 amount) external {
    uint256 available = balances[msg.sender];
    if (available < amount) {
        revert InsufficientBalance(available, amount);
    }
    balances[msg.sender] = available - amount;
}

Custom errors have three advantages. They are cheaper than strings (the error is identified by a 4-byte selector computed from its signature, plus the encoded arguments). They carry structured data that tools and tests can decode. And they read well, because the name describes the failure. Newer compiler versions also allow require(condition, CustomError(...)), but the if (...) revert Error(...) form works everywhere and is the common style.

Panics

Besides errors you write, the compiler inserts checks that revert with a panic code:

Code Meaning
0x01 A failed assert
0x11 Arithmetic overflow or underflow (outside unchecked)
0x12 Division or modulo by zero
0x21 Converting a number to an invalid enum value
0x31 pop() on an empty array
0x32 Array index out of bounds

See Integers, Overflow and Checked Math for 0x11. Seeing a panic in a test is a signal to look for a missing check, not to catch it.

try / catch

A revert normally travels up and cancels the whole transaction. When you call another contract or create one, you can catch the failure instead of bubbling it up:

SOLIDITY
try other.riskyCall(7) returns (uint256 result) {
    // success: use result
} catch Error(string memory reason) {
    // revert with a reason string
} catch Panic(uint256 code) {
    // a panic, such as 0x11
} catch (bytes memory data) {
    // anything else, including custom errors
}

Two limits are worth remembering. try works only on external calls and contract creation, not on internal function calls. And errors inside your own code in the success block are not caught by the same try. Only catch a failure when you know what to do about it, such as skipping one payee in a batch. Silently swallowing errors hides bugs.

Stand-ins that show rollback

The real EVM cannot run here, so the TryIts below are JavaScript stand-ins. The first one models the core promise: take a snapshot of the state, run the call, and restore the snapshot if it throws. It also decodes a custom error with parameters.

JS State rolls back when a call reverts

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The failed transfer changed Alice's balance before it threw, yet after the rollback she still has 70. The calls counter was also restored, which shows that a revert undoes every change, not just the failing line.

The second stand-in compares require-style checks, assert and try/catch classification, sorting errors into the same buckets Solidity uses.

JS require, assert and try/catch buckets

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What is real: revert semantics (everything undone, gas still paid), the difference between require and assert, panic codes and the catch buckets. What is the stand-in: a structuredClone snapshot instead of the EVM's journaled state, thrown JavaScript objects instead of ABI-encoded error data, and no gas accounting.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to storage changes made earlier in a call that later reverts?

    A revert, however it is triggered, rolls back all state changes of that call frame. Only the gas already spent is kept as the fee.
  2. 2. Which is the best fit for checking that a caller passed a non-zero amount?

    require is for conditions a caller could break, such as inputs and permissions. assert is for invariants that should never be false in correct code.
  3. 3. Why are custom errors usually preferred over long require strings?

    A custom error is identified by a 4-byte selector and ABI-encoded arguments, which costs less than storing and returning a string, and tools can decode its fields.
  4. 4. Where can try/catch be used?

    try/catch handles failures of calls to other contracts and of new creation. For your own code you use require and revert, and let the caller handle it.
  5. 5. Why is an unbounded loop over a user-growable array dangerous?

    Gas cost grows with each iteration. Once the array is large enough, the call needs more gas than a block allows and can never succeed.

Summary

  • Conditions must be real bool values, and loops cost gas on every iteration; avoid unbounded loops over user-growable data.
  • A revert undoes all state changes of the call but the gas used is still paid.
  • Use require for inputs and permissions, revert for branching logic, and assert for invariants.
  • Custom errors (error Name(args), revert Name(args)) are cheaper than strings and carry structured data.
  • Compiler checks revert with panic codes such as 0x11 (overflow) and 0x32 (index out of bounds).
  • try/catch handles failures of external calls and contract creation; catch only what you can handle.

Next: msg.sender, msg.value and Global Variables.