Error Handling

Learn error handling in Solidity.

Solidity incorporates robust error management features to handle both build-time and runtime errors. While syntax errors are checked during the conversion of Solidity to bytecode. Runtime errors such as out-of-gas, data-type overflow, divide-by-zero, and array-out-of-index are typically encountered during contract execution. In earlier versions, error handling relied on the throw statement, but newer versions have introduced additional constructs like assert(), require(), and revert() for more efficient and expressive error handling.

The require() statement

The require() statement in Solidity establishes conditions that must be satisfied before a function can execute. It acts as a constraint, evaluating a boolean expression and triggering an exception if the condition is false. The require() statement is a vital tool for enforcing constraints and validating inputs. For example, a developer might use the require() statement to check:

  • Improperly called function: If a function is incorrectly called, resulting in an exception, the require() statement can be utilized to halt execution and revert to the initial state.

  • Incomplete contract construction: When the new keyword is used to construct a contract, but the process isn’t completed correctly, the require() statement can handle this scenario.

  • Codeless contract targeting external function: If an external function is the target of a codeless contract, the require() statement helps identify and handle such situations.

  • Ether transfer and the .transfer() function: Situations like transferring ethers to a contract using the open-getter function or a failed .transfer() procedure can be managed with require().

  • An assert() statement with a false condition: When an assert() statement is invoked with a false-producing situation, the require() statement can serve as an alternative error-handling mechanism.

  • Initialization of variables to zero: When a function initializes variables to zero, and it’s invoked, a require() statement can ensure proper initialization.

  • Enum value validation: If a large or invalid value is attempted to be assigned to an enum, a require() statement can catch and handle this error.

  • Division by zero or modulo: Situations involving division by zero or modulo operations are handled using the require() statement.

  • Array index validation: When an excessively large or negative index is used to retrieve an array, the require() statement ensures proper array index validation.

Get hands-on with 1200+ tech skills courses.