Try Catch

# Try Catch

try / catch só pode captar erros de chamadas de função externa e criação de contrato.

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

// Contrato externo usado para exemplos de try / catch
contract Foo {
    address public owner;

    constructor(address _owner) {
        require(_owner != address(0), "endereço inválido");
        assert(_owner != 0x0000000000000000000000000000000000000001);
        owner = _owner;
    }

    function myFunc(uint x) public pure returns (string memory) {
        require(x != 0, "falah require");
        return "meu func foi chamado";
    }
}

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

    Foo public foo;

    constructor() {
        // Este contrato Foo e usado como exemplo de try catch com chamada externa
        foo = new Foo(msg.sender);
    }

    // Exemplo de try / catch com chamada externa
    // tryCatchExternalCall(0) => Log("falha na chamada externa")
    // tryCatchExternalCall(1) => Log("minha funcao foi chamada")
    function tryCatchExternalCall(uint _i) public {
        try foo.myFunc(_i) returns (string memory result) {
            emit Log(result);
        } catch {
            emit Log("falha na chamada externa");
        }
    }

    // Exemplo de try / catch com criacao de contrato
    // tryCatchNewContract(0x0000000000000000000000000000000000000000) => Log("ebdereco invalido")
    // tryCatchNewContract(0x0000000000000000000000000000000000000001) => LogBytes("")
    // tryCatchNewContract(0x0000000000000000000000000000000000000002) => Log("Foo criado")
    function tryCatchNewContract(address _owner) public {
        try new Foo(_owner) returns (Foo foo) {
            // voce pode usar a variavel foo aqui
            emit Log("Foo criado");
        } catch Error(string memory reason) {
            // pega a falha revert() e require()
            emit Log(reason);
        } catch (bytes memory reason) {
            // pega a falha assert()
            emit LogBytes(reason);
        }
    }
}

# Teste no Remix

Last Updated: 22/01/2024 22:26:13