Ethereum: Understanding “try catch, function returns X values” number

Disclaimer:

This article is only for training purposes and should not be used as investment advice. The Ethereum community relys on open source code, and such questions may sometimes be due to misunderstandings or misunderstandings.

As any developer knows, the programming languages ​​in the programming languages ​​are the types of recovery and variable notifications are important aspects of the code readability and maintenance. However, there is less well-known thing about Ethereum-intelligent contractual language stability that can lead to unexpected behavior: “Try the catch, the function returns X values, but returns the X-1 variables of the expression.”

Problem:

In the permanent functions, the functions return multiple values ​​(x), and then the test-fine block is used to handle these cases. However, the function itself proclaims only one variable (we call it “x”. This can lead to confusion when trying to fix a mistake.

For example:

`Solidity

Agreement MyContract {

Function MyFunction () Public Returns (INT X) {

// some code here …

int y = 5;

Try {

if (y> 10) {

Throw std :: Runtime_error (“Something went wrong!”);

}

} catch (Const std :: exception & e) {

Restore “Error closed!”;

}

}

}

`

In this case, when the “Try Catch” block is performed, it tries to determine the value of the “x". However, due to the changing announcement of the function, "X" has only one value (5). As a result, you get an unexpected error: "Variable 'x' does not indicate the reported variable."

Solution:

In order to solve this problem, you must edit the signature of the function and the 'return' clause. Here::

Solidity

Agreement MyContract {

Function MyFunction () Public Returns (INT X) {

// some code here …

int y = 5;

Try {

if (y> 10) {

Throw std :: Runtime_error (“Something went wrong!”);

}

} catch (Const std :: exception & e) {

Restore “Error closed!”;

} Else {

return x; // returns the declared value ‘x’

}

}

}

`

In this revised function signature, we have explicitly declared the “x” variable type int. Then we return the “X” real value in the “return” clause.

Additional Tips:

By understanding and solving this problem, you will significantly improve the readability of the code and error correction capabilities while working with Ethereum Smart contracts.

Leave a Reply

Your email address will not be published. Required fields are marked *