原文标题:《 Solidity 极简入门: 15. 异常 》
Original author: 0xAa 
I've been relearning Solidity recently to consolidate the details and also write a "Solidity Minimality Primer" for kids to use (programming geeks can find another tutorial) and update 1-3 sessions every week.
All open source code and tutorial github:github.com/AmazingAng/WTFSolidity
In this session we'll introduce three solidity methods for throwing exceptions: error, require, and assert, and compare the GAS consumption of the three methods.
Writing smart contracts often brings out bugs. Exception commands in Solidity help us debug.
The Error is solidity New content added in version 0.8 makes it easy and efficient (GAS saving) to explain the reasons for operation failures to users. People can define exceptions outside of Contracts. In the following, we define a TransferNotOwner exception that will throw an error when the user tries to transfer money without being the owner of the token:

Error must be used with the revert command in this execution.

We define a transferOwner1() function that checks if the owner of the token is the initiator, and if not, throws a TransferNotOwner exception; If it is, the money will be transferred.
The require command is solidity&NBsp; A common method of throwing exceptions prior to version 0.8, it is still used by many major contracts. It works well, but the only downside is that gas is higher than error as the length of the string describing the exception increases. Use: require(check condition, "description of exception"). If the check condition does not hold, an exception will be thrown.
Let's rewrite the transferOwner function above with the require command:

The assert command is generally used by programmers writing program debugging because it cannot explain the cause of an exception thrown (fewer strings than require). Its use is simple, assert, and it throws an exception when the check does not hold.
Let's rewrite the transferOwner function above with assert:

Let's compare the GAS consumption of the three exceptions by simply deploying the contract and running each of the three versions of the write transferOwner function.
Error method GAS consumption: 24445require method GAS consumption: 24743Assert method GAS consumption: 24446
We can see that ERROR method has the least gas cost, followed by Assert, and require method consumes the most gas! Therefore, ERROR can not only tell the user why an exception was thrown, but also save GAS. Use it!
In this session we'll introduce three solidity methods for throwing exceptions: error, require, and assert, and compare the GAS consumption of the three methods. Conclusion: ERROR can not only tell the user why an exception was thrown, but also save GAS.
The original link
Welcome to join the official BlockBeats community:
Telegram Subscription Group: https://t.me/theblockbeats
Telegram Discussion Group: https://t.me/BlockBeats_App
Official Twitter Account: https://twitter.com/BlockBeatsAsia
