This is Solidity Tutorial series article 9th describes solidity error handling. Solidity series complete list of articles please scan the QR code below to view.
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 is the way in which a program error is handled, 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:
-
revert function can be used to mark an error and fallback the current call
- P style= "margin-top:0px; margin-bottom:0px; padding:0px; Box-sizing:border-box; Color:rgb (79, 79, 79); line-height:26px; text-align:justify; Clear:both; Min-height:1em; " > use throw Keyword throws an exception (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:
1 2 3 4 5 6 7 8 9 Ten One
|
pragma solidity ^0.4. 0;
contract Sharer { function sendhalf(address addr) public payable returns (uint balance) { require(msg.value% 2 = = 0); //Only allowed even UINT 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:
First open the remix, paste in the code, click Create Contract. Such as:
Run Test 1: Append 1wei (odd) to call Sendhalf, an exception will occur, such as:
Run Test 2: Attach 2wei to call Sendhalf, run normally.
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:
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]
Accesses a fixed-length bytesn if the ordinal is out of bounds, or a negative ordinal value.
The divisor is 0, such as 5/0 or 23 0.
Moves a negative value to a binary. such as:5<<i; I is-1 o'clock.
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
If you call a variable that does not initialize the intrinsic type of the function.
False if the argument to assert is called
Require type exception
An exception of type require is automatically generated in the following scenario:
Call throw
If the argument to call require is False
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.
If there is a 3rd reason for creating a new contract using new, it does not complete properly.
If an external function call is called, the called object does not contain code.
If the contract does not have the payable modifier, the public function receives the etheric currency (including the constructor, and the fallback function).
If the contract receives the etheric currency through a public getter function (public getters funciton).
If the . Transfer () execution fails
When an Assert type exception occurs, solidity performs an invalid operation (instruction 0xFE).
In either of these 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).
Smart Contract Language Solidity Tutorial Series 9-Error handling