- Use assert() to prevent something bad from happening:
assert(condition);
- Use it to check conditions such as integer overflow/underflow:
pragma solidity ^0.4.24;
contract TestException {
function add(uint _a, uint _b) returns (uint) {
uint x = _a + _b;
assert(x > _b);
returns x;
}
}
You should not use assert() blindly for checking overflow/underflow. It should be used only if you think that previous require or if checks would make it impossible.
- Use it to check invariants in the contract. One example is to verify the contract balance against the total supply:
assert(address(this).balance >= totalSupply);
- assert is commonly used to validate state after making changes. It helps in preventing conditions that should never be possible. In an ideal scenario, the contract should never reach a failing assert statement. If this happens, there is a bug in your contract that you should fix.
- Generally, use assert towards the end of your function and use it less often.
- assert() uses the 0xfe opcode to cause an error condition if something fails.
- The opcode will consume all available gas for the call and revert the state changes made before the exception.