3 min read

Try Catch

Introduction

Solidity is a programming language used to write smart contracts for Ethereum blockchain. It is an object-oriented, high-level language with similarities to JavaScript and C++. Like any other programming language, Solidity also has errors and exceptions, which need to be handled properly. In this blog post, we will explain how to use the 'try catch' statement in Solidity 0.8.16 to handle errors and exceptions in a smart contract.

The 'try catch' statement

The 'try catch' statement is a feature introduced in Solidity version 0.6.0 that allows developers to handle errors and exceptions in a smart contract. It works similarly to the try-catch statement in other programming languages.

The syntax for using the 'try catch' statement is as follows:

try expression returns (bool) {
    // code block to execute
} catch Error(string memory reason) {
    // code block to handle error
} catch (bytes memory lowLevelData) {
    // code block to handle exception
}

Here, 'expression' refers to the code that might cause an error or exception. If the code executes successfully, the 'try' block returns 'true'. If an error or exception occurs, the corresponding 'catch' block is executed.

The 'catch Error' block is executed if the error is caused by the 'require', 'revert', or 'assert' statements, and the 'catch' block is executed if the error is caused by a low-level call.

Using 'try catch' in Simple Storage Contract

A Simple Storage Contract is a basic smart contract that allows users to store and retrieve a value on the blockchain. Let's use this contract as an example to demonstrate how to use 'try catch' to handle errors.

// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;

contract SimpleStorage {
    uint256 public storedValue;

    function store(uint256 _value) public {
        require(_value > 0, "Value must be greater than 0");
        storedValue = _value;
    }

    function retrieve() public view returns (uint256) {
        return storedValue;
    }
}

In this contract, the 'store' function allows users to store a value on the blockchain. The function requires that the value is greater than 0. If the value is less than or equal to 0, the 'require' statement will fail and the function will revert.

To handle this error, we can use the 'try catch' statement as follows:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;

contract SimpleStorage {
    uint256 public storedValue;

    function store(uint256 _value) public {
        try this.storeValue(_value) returns (bool success) {
            // If the transaction was successful, nothing happens here
        } catch Error(string memory reason) {
            // If the require statement failed, the error is caught here
            revert(reason);
        } catch (bytes memory /*lowLevelData*/) {
            // Other types of errors are caught here
            revert("Unknown error");
        }
    }

    function retrieve() public view returns (uint256) {
        return storedValue;
    }

    function storeValue(uint256 _value) internal {
        require(_value > 0, "Value must be greater than 0");
        storedValue = _value;
    }
}

In this code, we use the 'try catch' statement to handle the error that occurs if the value passed to the 'store' function is less than or equal to 0. The 'try' block wraps the 'storeValue' function call. If the function call executes successfully, nothing happens in the 'try' block.

If the 'require' statement fails, the corresponding 'catch' block is executed, and the function reverts with the error message "Value must be greater than 0." If any other type of error occurs, the 'catch' block is executed, and the function reverts with the error message "Unknown error."

Using 'try catch' in Uniswap Example

Uniswap is a decentralized exchange protocol built on Ethereum blockchain that allows users to trade cryptocurrencies without the need for a centralized intermediary. Uniswap uses the 'try catch' statement in its smart contract to handle errors and exceptions.

Here's a simple example from the Uniswap smart contract that demonstrates how to use 'try catch' to handle an error:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;

contract Uniswap {
    function swap(uint256 amountIn, uint256 amountOutMin, address[] memory path, address to, uint256 deadline) external returns (uint256[] memory amounts) {
        try IUniswapV2Router02(router).swapExactTokensForTokens(
            amountIn,
            amountOutMin,
            path,
            to,
            deadline
        ) returns (uint256[] memory _amounts) {
            return _amounts;
        } catch {
            revert("Uniswap: Swap failed");
        }
    }
}

In this code, the 'swap' function is used to swap one ERC20 token for another. The function calls the 'swapExactTokensForTokens' function from the Uniswap V2 Router smart contract, which executes the swap.

The 'try' block wraps the 'swapExactTokensForTokens' function call. If the function call executes successfully, the 'try' block returns the amount of output tokens received by the user. If an error occurs, the 'catch' block is executed, and the function reverts with the error message "Uniswap: Swap failed."

Conclusion

In conclusion, the 'try catch' statement in Solidity 0.8.16 allows developers to handle errors and exceptions in a smart contract. It is an essential feature that helps ensure the security and reliability of smart contracts. Using the Uniswap example, we can see how the 'try catch' statement can be used to handle errors and exceptions in real-world smart contracts.

Feedback

Have feedback? Found something that needs to be updated, accurate, or explained?

Join our discord and share what can be improved.

Any and all feedback is welcomed.