0

Have the following strange problem: I'd like to implement a try-catch block in Solidity (>= 0.8.0) as follows:

    try myFunction(list1, 3, 0) returns (uint256 _value) {
    {
        emit Log("Success");
    } catch Error(string memory _err) {
        emit Log(_err);
    } catch (bytes memory _err) {
        emit LogBytes(_err);
    }

Comparing this to the various examples available online, this should acctually be correct, IMHO. However, when compiling with Hardhat, I get the following error:

ParserError: Expected primary expression.
 } catch Error(string memory _err) {
   ^^^^^

Have checked, and double-checked the syntax, compared with other similar ParseErrors, but have no clue what I'm doing wrong here. Any help would be greatly appreciated!

2 Answers 2

2

just delete one of the {, you have two:

   try myFunction(list1, 3, 0) returns (uint256 _value) {// 1 
    {//2
        emit Log("Success");

Hope it helps

2
  • Can't believe that I didn't see this. Literavally wasted several hours!
    – Peter K.
    Jan 29, 2023 at 19:53
  • Glad to have helped!! Similar things happen to me all the time!
    – donoso.eth
    Jan 29, 2023 at 21:26
0

It seems like there is an issue with the syntax of your try-catch block in Solidity. The error message is indicating that it is expecting a primary expression where the "catch" keyword is used.

One possible issue could be that you are using the "catch" keyword in the wrong context. In Solidity, the "catch" keyword is used to handle exceptions thrown by the "require()" or "revert()" functions, not to handle the return value of a function like "myFunction()".

Instead of using a try-catch block, you can use the "require()" or "revert()" functions to handle errors that occur within the "myFunction()" call. You can check the return value of the function and emit an event to log the error message.

(bool success, uint256 _value) = myFunction(list1, 3, 0);
require(success, "Error: myFunction failed.");
emit Log("Success");

Alternatively, you can use a library for error handling like SafeMath that provides a require() method that reverts with a message and also check for errors in the myFunction and revert with a message.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.