-
bitcoin $87959.907984 USD
1.34% -
ethereum $2920.497338 USD
3.04% -
tether $0.999775 USD
0.00% -
xrp $2.237324 USD
8.12% -
bnb $860.243768 USD
0.90% -
solana $138.089498 USD
5.43% -
usd-coin $0.999807 USD
0.01% -
tron $0.272801 USD
-1.53% -
dogecoin $0.150904 USD
2.96% -
cardano $0.421635 USD
1.97% -
hyperliquid $32.152445 USD
2.23% -
bitcoin-cash $533.301069 USD
-1.94% -
chainlink $12.953417 USD
2.68% -
unus-sed-leo $9.535951 USD
0.73% -
zcash $521.483386 USD
-2.87%
How to handle errors in Solidity? (require, revert, assert)
Solidity provides `require`, `revert`, and `assert` for error handling, ensuring secure and predictable smart contract execution.
Jul 20, 2025 at 05:00 am
Understanding Error Handling in Solidity
Solidity, the primary programming language for Ethereum smart contracts, provides several mechanisms for error handling. These mechanisms are crucial for ensuring that contracts behave predictably and securely when unexpected or invalid conditions occur. The main tools available for error handling in Solidity are require, revert, and assert. Each of these functions serves a different purpose and should be used appropriately based on the situation.
Using require for Input Validation
The require function is primarily used to validate inputs and conditions before executing a function's core logic. If the condition provided to require evaluates to false, the transaction is reverted, and any changes made to the state are rolled back. Additionally, require allows developers to provide a custom error message.
function transfer(address to, uint amount) public {
require(amount > 0, 'Amount must be greater than zero');
require(balance[msg.sender] >= amount, 'Insufficient balance');
balance[msg.sender] -= amount;
balance[to] += amount;
}
In this example, require ensures that the sender has sufficient balance and that the amount being transferred is valid. If either condition fails, the transaction reverts with a clear error message.
Employing revert for Custom Error Conditions
The revert function offers more flexibility than require by allowing developers to revert execution at any point within a function. It is especially useful when dealing with complex logic or multiple conditions that may not be easily handled by a single require statement.
function withdraw(uint amount) public {
if (amount > balance[msg.sender]) {
revert('Insufficient funds for withdrawal');
}
if (block.timestamp
}
In this scenario, revert is used to handle two distinct conditions that could prevent a withdrawal. Each condition is evaluated separately, and a specific message is returned when the condition fails.
Utilizing assert for Internal Error Detection
The assert function is intended for checking invariants and catching internal errors that should never occur under normal circumstances. Unlike require and revert, using assert consumes all the gas provided in the transaction when triggered. Therefore, it should be reserved for situations where a critical bug is suspected.
function calculateSum(uint a, uint b) internal pure returns (uint) {
uint sum = a + b;
assert(sum >= a);
return sum;
}
In this function, assert ensures that the addition operation does not result in an underflow or overflow. If such an anomaly occurs, the transaction reverts, indicating a potential bug in the code.
Differences Between require, revert, and assert
Understanding the distinctions between require, revert, and assert is essential for effective error handling in Solidity:
- Gas Consumption:
requireandrevertonly consume gas up to the point of the error, whileassertconsumes all provided gas. - Use Cases:
requireis best for input validation,revertfor custom conditions, andassertfor internal logic checks. - Error Messages: Both
requireandrevertallow for custom error messages;assertdoes not provide a way to return custom messages in older versions of Solidity (prior to 0.8.0).
Choosing the appropriate error handling method ensures that your smart contracts are both secure and efficient.
Custom Errors in Solidity
Starting from Solidity 0.8.0, developers can define custom error types, which are more gas-efficient and readable than string-based error messages. Custom errors are defined using the error keyword and can be used in conjunction with revert.
error InsufficientBalance(uint requested, uint available);error FundsLocked(uint releaseTime, uint currentTime);
function withdraw(uint amount) public {
if (amount > balance[msg.sender]) {
revert InsufficientBalance(amount, balance[msg.sender]);
}
if (block.timestamp
}
By using custom errors, developers can provide structured error information that is both easy to understand and efficient in terms of gas usage.
Frequently Asked Questions
Q: Can I use assert for input validation?A: No, assert should not be used for input validation. It is designed for internal checks and should only be used to detect unreachable code or critical bugs.
Q: How do custom errors save gas compared to string messages?A: Custom errors are encoded as four-byte selectors, similar to function signatures, which are much shorter and cheaper than full string messages. This results in lower gas costs when an error is triggered.
Q: What happens if I don’t handle errors in my contract?A: If errors are not properly handled, invalid or unexpected conditions may lead to incorrect state changes, loss of funds, or vulnerabilities that can be exploited by attackers.
Q: Can I combine require and revert in the same function?A: Yes, require and revert can be used together in the same function. require is typically used for simple condition checks, while revert is used for more complex or conditional reverts later in the function.
Disclaimer:info@kdj.com
The information provided is not trading advice. kdj.com does not assume any responsibility for any investments made based on the information provided in this article. Cryptocurrencies are highly volatile and it is highly recommended that you invest with caution after thorough research!
If you believe that the content used on this website infringes your copyright, please contact us immediately (info@kdj.com) and we will delete it promptly.
- Bitcoin, eCash Fork, and Airdrop Dynamics: A Deep Dive into Crypto's Latest Controversies
- 2026-05-03 12:55:01
- Consensus 2026 Miami: Web3, Blockchain, Cryptocurrency, NFTs, Metaverse, Conference, May 5th — Where Wall Street Meets the Digital Frontier
- 2026-05-02 12:45:01
- Fed Holds Rates Steady, Triggering Bitcoin Price Drop Amidst Geopolitical Tensions
- 2026-05-01 06:45:01
- Bitcoin Miners Electrify the Grid: Ohio Gas Plant Acquisition Powers Up a New Era for Digital Gold
- 2026-05-01 00:45:01
- MegaETH's MEGA Token Hits the Big Apple: Setting New Performance Benchmarks for Real-Time Blockchain
- 2026-05-01 00:55:01
- Solana's Slippery Slope: Price Prediction Points to Resistance Loss and Potential Further Drops
- 2026-05-01 06:45:01
Related knowledge
What Is a Funding Rate Flip? Why It Often Signals Changing Market Sentiment
Jun 14,2026 at 03:57am
Market Volatility Patterns1. Bitcoin price swings often exceed 10% within 24-hour windows during major macroeconomic announcements. 2. Ethereum’s vola...
How to Recognize Market Manipulation Signals in Crypto Futures Markets
Jun 12,2026 at 05:26pm
Bitcoin Halving Mechanics1. Bitcoin’s protocol enforces a fixed issuance schedule where block rewards are cut in half approximately every 210,000 bloc...
What Is Leverage Trapping? Why Retail Traders Often Get Caught
Jun 12,2026 at 11:53pm
Market Volatility Patterns1. Bitcoin price swings often exceed 5% within a 24-hour window during high-liquidity events such as ETF approval announceme...
What Is a Breakout Trade? How Futures Traders Capture Large Price Moves
Jun 13,2026 at 05:19am
Understanding Breakout Mechanics in Crypto Futures1. A breakout occurs when Bitcoin or altcoin price decisively breaches a well-established resistance...
What Is the Best Stop-Loss Strategy for High-Leverage Futures Positions?
Jun 14,2026 at 02:19pm
Stop-Loss Mechanics in High-Leverage Futures Trading1. Stop-loss placement must align with the statistical properties of price diffusion—not arbitrary...
How to Trade Crypto Futures During Major Economic Announcements
Jun 12,2026 at 10:50pm
Market Volatility Patterns1. Bitcoin price swings often exceed 5% within a single 24-hour window during high-liquidity events such as halving announce...
What Is a Funding Rate Flip? Why It Often Signals Changing Market Sentiment
Jun 14,2026 at 03:57am
Market Volatility Patterns1. Bitcoin price swings often exceed 10% within 24-hour windows during major macroeconomic announcements. 2. Ethereum’s vola...
How to Recognize Market Manipulation Signals in Crypto Futures Markets
Jun 12,2026 at 05:26pm
Bitcoin Halving Mechanics1. Bitcoin’s protocol enforces a fixed issuance schedule where block rewards are cut in half approximately every 210,000 bloc...
What Is Leverage Trapping? Why Retail Traders Often Get Caught
Jun 12,2026 at 11:53pm
Market Volatility Patterns1. Bitcoin price swings often exceed 5% within a 24-hour window during high-liquidity events such as ETF approval announceme...
What Is a Breakout Trade? How Futures Traders Capture Large Price Moves
Jun 13,2026 at 05:19am
Understanding Breakout Mechanics in Crypto Futures1. A breakout occurs when Bitcoin or altcoin price decisively breaches a well-established resistance...
What Is the Best Stop-Loss Strategy for High-Leverage Futures Positions?
Jun 14,2026 at 02:19pm
Stop-Loss Mechanics in High-Leverage Futures Trading1. Stop-loss placement must align with the statistical properties of price diffusion—not arbitrary...
How to Trade Crypto Futures During Major Economic Announcements
Jun 12,2026 at 10:50pm
Market Volatility Patterns1. Bitcoin price swings often exceed 5% within a single 24-hour window during high-liquidity events such as halving announce...
See all articles














