3分钟Solidity: 6.1 Try Catch

23 阅读2分钟

欢迎订阅专栏3分钟Solidity--智能合约--Web3区块链技术必学

如需获取本内容的最新版本,请参见 Cyfrin.io 上的Try Catch(代码示例)

try/catch 只能捕获外部函数调用和合约创建中的错误。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

// 用于 try / catch 示例的外部合约
contract Foo {
    address public owner;

    constructor(address _owner) {
        require(_owner != address(0), "无效地址");
        assert(_owner != 0x0000000000000000000000000000000000000001);
        owner = _owner;
    }

    function myFunc(uint256 x) public pure returns (string memory) {
        require(x != 0, "require failed");
        return "my func was called";
    }
}

contract Bar {
    event Log(string message);
    event LogBytes(bytes data);

    Foo public foo;

    constructor() {
        // 该Foo合约用于演示带有外部调用的try catch示例
        foo = new Foo(msg.sender);
    }

    // 外部调用try/catch示例
    // tryCatchExternalCall(0) => 日志记录("外部调用失败")
    // tryCatchExternalCall(1) => 日志记录("我的函数被调用了")
    function tryCatchExternalCall(uint256 _i) public {
        try foo.myFunc(_i) returns (string memory result) {
            emit Log(result);
        } catch {
            emit Log("external call failed");
        }
    }

    // 合约创建时的try/catch示例
    // tryCatchNewContract(0x0000000000000000000000000000000000000000) => 日志("无效地址")
    // tryCatchNewContract(0x0000000000000000000000000000000000000001) => 日志字节("")
    // tryCatchNewContract(0x0000000000000000000000000000000000000002) => 日志("Foo已创建")
    function tryCatchNewContract(address _owner) public {
        try new Foo(_owner) returns (Foo foo) {
            // 你可以在这里使用变量 foo
            emit Log("Foo created");
        } catch Error(string memory reason) {
            // 捕获失败的 revert() 和 require()
            emit Log(reason);
        } catch (bytes memory reason) {
            // 捕获失败的断言
            emit LogBytes(reason);
        }
    }
}

Remix Lite 尝试一下

solidity-try/catch


END