Try Catch in Solidity

A try catch is a common error handling mechanism used in many programming languages, and Solidity is no exception. In this article, we will explore the benefits of using try-catch in Solidity and how to implement it in your smart contracts.

Benefits of Try Catch in Solidity

One of the primary benefits of using try-catch in Solidity is the ability to handle and recover from unexpected errors. In a smart contract, errors can occur due to a variety of reasons such as invalid input, unexpected state changes, and external factors like network congestion. Without proper error handling, these errors can lead to unexpected behavior and even security vulnerabilities. Try Catch can only catch errors from external function calls and contract creation.

Using try-catch, developers can anticipate and handle these errors, allowing for a more robust and secure smart contract. For example, if a user submits an invalid input to a function, a try-catch block can be used to catch the error and return an appropriate message to the user. This not only improves the user experience but also prevents potential security vulnerabilities.

Implement Try Catch

To implement try-catch in Solidity, the require() function is used in conjunction with the catch keyword. The require() function is used to enforce a condition and will revert the entire transaction if the condition is not met. The catch keyword is used to specify a specific error message to be returned if the require() function reverts the transaction.

Here is an example of how to implement try-catch in a Solidity function:

function withdraw(uint amount) public {
    require(amount <= balance, "Insufficient funds");
    // Withdraw logic
}

Try it in Remix

In this example, the function withdraw() uses a require() function to check if the amount requested to withdraw is less than or equal to the current balance. If the condition is not met, the transaction will be reverted and the error message “Insufficient funds” will be returned.

To test this try-catch implementation we can use the following test scenario:

pragma solidity ^0.8.0;

contract TestTryCatch {
    uint public balance;

    function TestTryCatch() public {
        balance = 100;
    }

    function withdraw(uint amount) public {
        require(amount <= balance, "Insufficient funds");
        balance -= amount;
    }
}

Try it in Remix

In addition to require(), another way to implement try-catch in Solidity is by using the revert() function. This function can be used to revert the current transaction and return a specific error message. Here is an example of how to use the revert() function in a Solidity function:

function deposit(uint amount) public {
    if (amount <= 0) {
        revert("Invalid deposit amount");
    }
    // Deposit logic
}

Try it in Remix

In this example, the function deposit() checks if the amount to be deposited is less than or equal to zero. If the condition is met, the transaction will be reverted and the error message “Invalid deposit amount” will be returned.

To test this try-catch implementation we can use the following test scenario:

pragma solidity ^0.8.0;

contract TestTryCatch {
    uint public balance;

    function TestTryCatch() public {
        balance = 100;
    }

    function deposit(uint amount) public {
        if (amount <= 0) {
            revert("Invalid deposit amount");
        }
        balance += amount

Try it in Remix

Try Catch with External Functions

To implement try-catch in an external function, the require() function can be used in conjunction with the catch keyword. The require() function is used to enforce a condition and will revert the entire transaction if the condition is not met. The catch keyword is used to specify a specific error message to be returned if the require() function reverts the transaction.

Here is an example of how to implement try-catch in an external function:

function callFunction(address _contract, bytes memory _data) public {
    require(_contract.call(_data), "Error calling function");
}

Try it in Remix

In this example, the function callFunction() takes in an address of a contract and the data to be passed to the function. It then uses a require() function to check if the call was successful. If the call fails, the transaction will be reverted and the error message “Error calling function” will be returned.

To test this try-catch implementation, we can use the following test scenario:

pragma solidity ^0.8.0;

contract TestTryCatch {
    uint public balance;

    function TestTryCatch() public {
        balance = 100;
    }
    function testCallFunction() public {
        address payable _contract = address(this);
        bytes memory _data = abi.encodeWithSelector(bytes4(keccak256("withdraw()")), 2);
        callFunction(_contract, _data);
    }
}

Try it in Remix

In conclusion, using try-catch in an external function can improve the robustness and security of your smart contract interactions by anticipating and handling errors that may occur. By using the require() function in conjunction with the catch keyword, developers can ensure that their contract interactions are executed correctly and handle any errors that may occur.

Resources

Blockchain Networks

Below is a list of EVM compatible Mainnet and Testnet blockchain networks. Each link contains network configuration, links to multiple faucets for test ETH and tokens, bridge details, and technical resources for each blockchain. Basically everything you need to test and deploy smart contracts or decentralized applications on each chain. For a list of popular Ethereum forums and chat applications click here.

Ethereum test network configuration and test ETH faucet information
Optimistic Ethereum Mainnet and Testnet configuration, bridge details, etc.
Polygon network Mainnet and Testnet configuration, faucets for test MATIC tokens, bridge details, etc.
Binance Smart Chain Mainnet and Testnet configuration, faucets for test BNB tokens, bridge details, etc.
Fanton networt Mainnet and Testnet configuration, faucets for test FTM tokens, bridge details, etc.
Kucoin Chain Mainnet and Testnet configuration, faucets for test KCS tokens, bridge details, etc.

Web3 Software Libraries

You can use the following libraries to interact with an EVM compatible blockchain.