typestar

try/catch in Solidity

Guard external calls that may revert.

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

// try/catch guards external calls that may revert.
interface IWeather {
    function frostTonight() external view returns (bool);
}

contract FrostWatch {
    IWeather public oracle;
    bool public coversOut;

    constructor(address oracleAddress) {
        oracle = IWeather(oracleAddress);
    }

    function check() external {
        try oracle.frostTonight() returns (bool frost) {
            coversOut = frost;
        } catch {
            coversOut = true;  // no answer: protect the blossoms
        }
    }
}

How it works

  1. try oracle.frostTonight() returns (bool frost) binds success.
  2. The bare catch handles any revert or failure.
  3. The fallback choice is defensive: assume frost.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
497
Tokens
79
Three-star pace
55 tpm

At the three-star pace of 55 tokens a minute, this run takes about 86 seconds.

Type this snippet

Step 3 of 3 in The environment, step 23 of 28 in Language basics.

← Previous Next →

try/catch in other languages