Explicit Reverts
Part of the Fundamentals section of Coddy's Solidity journey. Lesson 47 of 53.
An if branch can call revert(message) to reject an invalid case explicitly. This is useful when the rejection condition is easier to read than its opposite. Place normal work after the guard so it runs only for acceptable input.
The statements in this excerpt run inside the provided main function.
uint256 chosen = 4;
if (chosen > 6) { revert("Choice too large"); }
console.log(chosen + 2);Four does not exceed six, so the rejecting branch is skipped. Execution reaches the console call. An explicit revert rejects the call just like a failed require; it is not a way to print a normal result.
revert ends the current call with failure instead of continuing normally.
Challenge
EasyReject value above 50 with revert and a useful message. For accepted input, print 50 minus value. All output tests are in range.
The tests pass arguments to main in this order: uint256 value. Each test starts with fresh contract state.
Use console.log for the requested output. Print only the requested values, one per line, with no extra labels unless the task specifies them.
Try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import "forge-std/console.sol";
contract Main {
function main(uint256 value) external view {
// Write your solution here.
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
Practice on your own: Solidity playground