try/catch en Solidity
Protege llamadas externas que pueden revertir.
// 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
}
}
}
Cómo funciona
try oracle.frostTonight() returns (bool frost)ata el éxito.- El
catchpelado maneja cualquier reversión o fallo. - La elección de respaldo es defensiva: asumir helada.
Palabras clave y builtins usados aquí
addressboolconstructorcontractexternalfunctionpublicreturnstrue
El intento, en números
- Líneas
- 24
- Caracteres a escribir
- 497
- Tokens
- 79
- Ritmo de tres estrellas
- 55 tpm
Al ritmo de tres estrellas de 55 tokens por minuto, este intento toma unos 86 segundos.
Paso 3 de 3 en El entorno; paso 23 de 28 en Fundamentos del lenguaje.