Skip to content

Understanding Try/Catch

There is a new concept in Solidity since Solidity 0.6, which allows for basic try/catch inside a Smart Contract. Before that you had to use constructs like address.call (which we will do later in the course as well). But here I quickly want to give you a hint of what's possible now with Error handling.

Let's create a Smart Contract which will always fail to execute.

Create a new file in Remix with the following content:

//SPDX-License-Idenfitier: MIT
pragma solidity 0.8.4;

contract WillThrow {
    function aFunction() public {
        require(false, "Error message");
    }
}

Now let's add a contract directly underneath that catches the error within a function call and instead emits an event with the error message. I am aware that we haven't covered events quite yet, so, let me quickly explain what happens. It will catch the error, and instead of unsuccessfully showing an error, it will successfully mine the transaction. During the transaction it will emit an event that shows the error message. You can see it later in the transaction logs.

//SPDX-License-Idenfitier: MIT
pragma solidity 0.8.4;

contract WillThrow {
    function aFunction() public {
        require(false, "Error message");
    }
}

contract ErrorHandling {
    event ErrorLogging(string reason);
    function catchError() public {
        WillThrow will = new WillThrow();
        try will.aFunction() {
            //here we could do something if it works
        }  catch Error(string memory reason) {
            emit ErrorLogging(reason);
        }
    }
}

Head over to the Deploy and Run Transactions Plugin and Deploy the "ErrorHandling" Contract:

You can see in the logs on the bottom right side that the transaction is mined successfully. And when you open the transaction details you see an event with the error message:

I know, this is a lot of new stuff which we haven't covered in depth yet. The point here is that Try/Catch fits into the exception handling and this is the most simplistic example I could come up with. It's something you should've seen before going on with the rest of the course. Now back to the content!


Last update: March 28, 2022