Condition and error verification

Solidity initially used the special keyword throw to stop and exit the contract execution when called. Since then, the functions assert(), require(), and revert() have been introduced (in Solidity 0.4.10), in order to enhance the error handling. Although the throw function is now being deprecated, you are still able to use it.

With all of these functions in place, we can use them equivalently, as follows:

You might have noticed that we have reversed the required conditional statement between, on the one hand, require() and assert(), and on the other hand, throw and revert(). In assert() and require(), we provide the statement that we want to be true, whereas throw and revert() behave like exit functions that you call when your condition isn't met.

The differences between these functions can be described as follows:

  • assert(bool condition): Throws if the condition is not met; this is to be used for internal errors. It uses up all remaining gas and reverts all changes.
  • require(bool condition): Throws if the condition is not met; this is to be used for errors in input or external components. Generously, it will refund the remaining gas to the caller.
  • revert(): Aborts execution and reverts state changes with a gas refund.
  • throw: Throws and consumes any remaining gas.

As revert() and require() both refund the unconsumed gas, they should be used to ensure valid conditions, whereas assert() should be used to check a harmful statement and to protect your contract, meaning that you can use assert to avoid overflow or underflow. Think of assert() as a handbrake that you use when something very wrong has happened, and the other functions as normal brakes.

An important feature that has been introduced in a newer Solidity version (0.4.22) is that you can return an argument to specify the error reason in your assert or require function:

require(msg.sender == owner, "the execution is reserved to the contract's owner");

if (msg.sender != owner) {
revert("the execution is reserved to the contract's owner");
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset