Smart Contract Language Solidity Tutorial Series 9-Error handling

Source: Internet
Author: User
Tags assert

This is Solidity Tutorial series article 9th describes solidity error handling.
For a complete list of articles in the solidity series, see Category-solidity.

Write in front

Solidity is the Ethereum Smart Contract programming language, you should know about Ethereum and smart contracts before reading this article.
If you don't understand, it's recommended that you look at Ethereum first.

Subscribe to the Blockchain technology column to read more comprehensive analysis articles.

What is error handling

Error handling refers to the way in which a program error occurs, solidity processing errors are different from our common language, and solidity is handling errors in a fallback state. When an exception occurs, the state changed by the current call (and all its child calls) is undone, and an error ID is returned to the caller. Note catching exceptions is not possible , so there is no try ... catch ....

Why do solidity deal with errors like this design?
We can understand blockchain as a distributed transactional database that is shared globally. Global sharing means that every person involved in this network can read and write records. If you want to modify the contents of this database, you must create a transaction, the transaction means that the changes to be made (if we want to modify two values at the same time) can only be fully applied or not at all.
Students who have studied the database should understand the meaning of the transaction, if you do not understand the word transaction, it is recommended that you search for "database transactions."
Solidity error handling is to ensure that each invocation is transactional.

How to Handle

Solidity provides two function asserts and require for conditional checking, and throws an exception if the condition is not met. The Assert function is often used to check for (test) internal errors, while the Require function checks whether the input variable or contract state variable satisfies the condition and validates the call to the external contract return value.
In addition, if we use assert correctly, there is a solidity analysis tool that can help us analyze the errors in the smart contract and help us to find bugs in the contract that are logically wrong.

In addition to two function asserts and require for conditional checking, there are two other ways to trigger an exception:

    1. The revert function can be used to mark an error and fallback the current call
    2. Throws an exception using the throw keyword (from version 0.4.13, the Throw keyword has been deprecated and will be eliminated in the future.) )

When an exception occurs in a child call, the exception automatically bubbles up. However, there are some exceptions: send, and the underlying function called call, Delegatecall,callcode, when an exception occurs, these functions return FALSE.

Note: Calling the underlying function Call,delegatecall,callcode on a nonexistent address will also return success, so we should always prioritize function presence checks when making calls.

Below is an example of how to use require to check the input criteria and assert for internal error checking:

pragma solidity^0.4.0;Contract Sharer{    function Sendhalf(Address addr) PublicPayablereturns(UINT balance){        require(msg.value % 2 == 0); //only allowed evenUINT Balancebeforetransfer=  This.Balance;        Addr.Transfer(msg.value/2);  //If it fails, an exception is thrown, and the following code is not executed        assert( This.Balance ==Balancebeforetransfer- msg.value/2);        return  This.Balance;    }}

Let's actually run and see how the exception happened:

    1. First open the remix, paste in the code, click Create Contract. Such as:

    2. Run Test 1: Append 1wei (odd) to call Sendhalf, an exception will occur, such as:

    1. Run Test 2: Attach 2wei to call Sendhalf, run normally.
    2. Run Test 3: Attach 2wei and sendhalf parameter for the current contract itself, the transfer is an exception because the contract cannot receive the transfer, the error is similar.
Assert type exception

An exception of the Assert type is automatically generated in the following scenario:

    1. If an array is crossed, or a negative ordinal value is accessed, such as I >= x.length or i < 0 o'clock access X[i]
    2. Accesses a fixed-length bytesn if the ordinal is out of bounds, or a negative ordinal value.
    3. The divisor is 0, such as 5/0 or 23 0.
    4. Moves a negative value to a binary. such as:5<<i; I is-1 o'clock.
    5. An integer that can be explicitly converted to an enumeration throws an exception if the value is too large and negative values are converted to an enumeration type
    6. If you call a variable that does not initialize the intrinsic type of the function.
    7. False if the argument to assert is called
Require type exception

An exception of type require is automatically generated in the following scenario:

    1. Call throw
    2. If the argument to call require is False
    3. If you call a function through a message, but in the process of the call, it does not end correctly (gas is insufficient, there is no match to the corresponding function, or the function that is called has an exception). The underlying operations, such as Call,send,delegatecall or Callcode, do not throw exceptions, but they will indicate failure by returning false.
    4. If there is a 3rd reason for creating a new contract using new, it does not complete properly.
    5. If an external function call is called, the called object does not contain code.
    6. If the contract does not have the payable modifier, the public function receives the etheric currency (including the constructor, and the fallback function).
    7. If the contract receives the etheric currency through a public getter function (public getters funciton).
    8. If the . Transfer () execution fails

When an exception of type require occurs, solidity performs a fallback operation (instruction 0xfd).
When an Assert type exception occurs, solidity performs an invalid operation (instruction 0xFE).
In both cases, EVM will recall all state changes. It is because the expected result does not happen, it is impossible to continue to execute safely. The atomicity of the trade must be guaranteed (consistent, or all, or no change at all, not just part of it), so all operations need to be undone so that the entire transaction has no effect.

Note that an exception of the Assert type consumes all gas, and require does not consume gas from the metropolitan version (Metropolis, which is the current version of the main network).

Reference documents
    • Solidity error Handling

Welcome to my knowledge of the planet. Blockchain discussion blockchain technology, and I will provide you with blockchain technical solution, as a star friend benefits, star friends can join the blockchain technology paid Exchange group.
In-depth blockchain-the system learns blockchain to create the best blockchain technology blog.

Smart Contract Language Solidity Tutorial Series 9-Error handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.