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
try oracle.frostTonight() returns (bool frost)binds success.- The bare
catchhandles any revert or failure. - The fallback choice is defensive: assume frost.
Keywords and builtins used here
addressboolconstructorcontractexternalfunctionpublicreturnstrue
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.
Step 3 of 3 in The environment, step 23 of 28 in Language basics.