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.14;
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-Identifier: MIT
pragma solidity 0.8.14;
contract WillThrow {
function aFunction() public pure {
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 one more thingā¦
Named Exceptions and Custom Errors
Another new concept is Named Exceptions. They are defined in your Contract, but they canāt be really caught (yet) by (try/catch), which somehow makes them problematic. I still think they are a great addition.
So, by default, when require evaluates to false, it will revert with a generic Error(string)
error. You can define other Errors here. Let me give you an example:
//SPDX-License-Identifier: MIT
pragma solidity 0.8.14;
contract WillThrow {
error ThisIsACustomError(string, string);
function aFunction() public pure {
revert ThisIsACustomError("Text 1", "text message 2");
}
}
With this, you can give certain arguments, like a state of balance or other things, to the outside world before aborting the transaction and rolling back.