Solidity — All About Errors Handling

Jean Cvllr
17 min readApr 15, 2023
photo by Sarah Kilian on Unsplash

This article is Part III of the “All About Errors” sub-series.

After looking at the different type of errors (Compile vs Runtime Errors), the different type of Solidity errors and the distinctions between them, we will now look at the different ways to handle them.

Solidity provides multiple built-in methods to handle errors, including assert(), require() and revert(). We will see in this article the difference between them, when each method should be used, and the benefits each provides. We will also look at handling errors from external calls (function call vs low-level calls).

Finally, we will briefly cover some scenarios you should be aware of when writing Solidity that can cause errors and bugs but where the Solidity code does not signal something is going wrong at runtime!

Table of content

- Introduction to Error Handling in Solidity
- Assert()
- How to use assert() in Solidity?
- Assert behaviour change since Solidity 0.8.0
- Using assert() for Formal Verification
- Final important notes on assert()
- Require()
- How to use require() in Solidity?
- Revert()
- Reverting in assembly
- Errors in external calls
- How to Bubble up errors from low-level calls?
- Edge cases with Account existence check
- Errors with arithmetic operations
- Bit shifts operations under/overflow but do not cause errors!
- Errors with ecrecover.
- References

Introduction to Error Handling in Solidity

Handling errors appropriately and accurately is crucial to any programming language. We often hear statements like:

  • “Write your catch block before you try block”
  • “throw and fail early”

Smart contracts usually hold large amounts of funds, handle important business logic and cannot be edited once deployed on the production main network. All of this gives highlights that smart contracts are mission-critical programs.

As a result, handling errors incorrectly in Ethereum and EVM environments is even less of an option.

Until solidity 0.4.x, the only way to handle errors was with throw.

--

--