Handling errors properly in solidity
Error handling is an essential part of every programming language. The general usage includes try
, catch
, and throw
statements, but solidity uses require
, revert
, and assert
methods to handle exceptions in the contract. Since Ethereum is a state machine, the exceptions that occur will revert all changes made to the state in the current call.
In this recipe, you will learn to handle exceptions using the require
, revert
, and assert
methods.
Getting ready
You need to have a working Ethereum installation for deploying and testing the smart contract. You can also use the Remix IDE to write and test the solidity code.
How to do it...
Solidity provides the require
, revert
, and assert
functions for handling exceptions and validations in smart contracts. Let's look into the usecase for each function and how they are handled by the solidity compiler.
require()
require()
is a conveniencefunctionused to check conditions and throw an exception if a condition is not met.- Earlier...