异常处理
try...catch... / throw
function tryCatchExternalCall(uint _i) public {
try foo.myFunc(_i) returns (string memory result) {
// ...
} catch {
// ...
}
}
require / revert / assert
contract A {
function testRequire(uint _i) public pure {
require(_i > 10, '_i error'); // 当 _i <= 10报错
}
function testRevert(uint _i) public pure {
if (_i > 10) {
revert('i need to be greater than 10'); // 不满足条件主动触发错误
}
}
function testAssert(uint _i) public pure {
assert(_i == 100); // 不满足assert内部条件的报错
}
}
自定义错误
contract A {
// 定义错误
error MyError(address caller, uint i);
function testCustomeError(uint _i) public view {
if (_i > 10) {
revert MyError(msg.sender, _i)
}
}
}