Solidity — All About Try / Catch

Jean Cvllr
9 min readApr 25, 2023
photo by Anthony Durant on Unsplash

This is Part IV of the All About Errors sub-series.

After looking at ways to handle errors at runtime, we will explore a specific type of error handling in Solidity: try {} catch {} . We will see how it can be used when doing to catch errors and creating new contracts.

We will look at how each type of Solidity runtime errors can be caught within the catch block using various syntax.

Table of content

- Introduction to Solidity try / catch
- How to use try / catch statement in Solidity?
- The optional "return" part of try / catch
- option 1: do not defines the returns part
- option 2: define a returns part
- Different types of catch blocks
- Generic catch { … } block
- Retrieving an Error(string) from a catch block
- Warning: Errors inside the try catch expressions are not caught!
- Important Gotchas and Culprits of try / catch

Introduction to Solidity Try Catch

Solidity supports exception handling with try / catch, but only for external function calls and contract creation calls.

The try catch syntax is available since version 0.6.2. It was added as a response to low-level calls, something many devs were already using.

In this case, the caller (a smart contract making the call) can react on failures and errors occurring in the callee (the smart contract being called) and react to such failures using the try / catch syntax.

How to use try / catch statement in Solidity?

The try keyword has to be followed by an expression representing:

  • either an external function call
  • or a contract creation → new ContractName()

It is also important to know that any local variables defined either inside the try or the catch clauses are not accessible outside these clause. They are scoped and accessible only inside the success or errors blocks they are…