Search code examples
solidityhardhat

Can try-catch not handle an error in solidity?


I have an internal function

function _somefunction() internal {
    if (address(attr) != address(0)) {
        try attr.maybedoesntexist() {
        } catch Error(string memory message) {
            emit SomethingFailed();
        } catch {
            emit SomethingFailed();
        }
    }
}

When I test this in hardhat I set attr to be a non-contract, but somehow the error function call to a non-contract account goes through the first catch and the whole thing reverts.

No other function uses attr and the error is completely dependent on whether attr is a contract account. Can catch actually not handle some errors?


Solution

  • Exceptions from calls to non-contracts are currently (v0.8) not caught by try/catch.

    You can validate whether the address is a contract, and only invoke calls on contracts:

    // length of attr's bytecode is 0, it's not a contract
    if (address(attr).code.length == 0) {
        return;
    }
    
    try attr.maybedoesntexist() {