Require / Revert / Assert
Explore Solidity error handling types — syntax, encoding, gas behavior, and usage guidance.
1// Basic require2require(msg.sender == owner);34// With message5require(amount > 0, "Amount must be positive");67// Multi-condition8require(balance >= amount, "Insufficient balance");9require(block.timestamp >= unlockTime, "Too early");1011// Custom error (0.8.26+)12require(amount > 0, InsufficientAmount());
Error(string) encoding:
- •Validating function inputs and parameters
- •Checking access control (msg.sender == owner)
- •Verifying preconditions before state changes
- •Checking external call return values
- •Internal invariant checks (use assert)
- •Complex error data (use custom errors)
- •Gas-sensitive operations (string messages cost extra)
require() validates conditions and reverts with a message. revert() explicitly aborts execution. Both use the REVERT opcode and refund remaining gas.
require is for expected failures (bad input), assert is for bugs (broken invariants). Since 0.8, both refund gas, but assert signals a code defect.
Introduced in 0.8.4, custom errors are gas-efficient alternatives to string messages. They use only 4 bytes for the selector plus ABI-encoded parameters.
Error data is ABI-encoded: Error(string) for require/revert messages, Panic(uint256) for assert, and custom selectors for user-defined errors.
Before Solidity 0.8.0, assert() consumed ALL remaining gas — making it essentially a gas bomb if triggered accidentally.