Roadmap › Solidity & Smart Contract Development › Module: Language Basics
Lessons in this course (11)
4. Errors, require, revert, assert and events
Intermediate★ Must knowLesson 4 of 11
solidity
error Unauthorized(address caller);
error InsufficientFunds(uint256 needed, uint256 available);
function pay(uint256 amount) external {
require(amount > 0, "Zero amount"); // input validation (string costs more gas)
if (balance[msg.sender] < amount) revert InsufficientFunds(amount, balance[msg.sender]); // custom error (0.8.4+), cheapest
assert(totalSupply >= balance[msg.sender]); // invariants that should NEVER fail (Panic error)
}
// try/catch for external calls
try oracle.latestPrice() returns (uint256 p) { price = p; }
catch Error(string memory reason) { emit OracleFailed(reason); }
catch (bytes memory) { emit OracleFailed("unknown"); }On revert, all state changes in the call are undone; gas used so far is consumed. Events (emit Transfer(from, to, amount)) write to transaction logs — cheap, not readable by contracts, but indexed by off-chain apps; up to 3 indexed parameters become searchable topics.