try / catch
By default, when an external call reverts, the revert bubbles up and your function fails too. try … catch lets you handle the failure instead: log it, fall back to another source, or skip a bad entry.
try feed.latestPrice() returns (uint256 price) {
// success: use price
} catch Error(string memory reason) {
// revert("…") or require(false, "…")
} catch Panic(uint256 code) {
// assert failure, overflow, division by zero, …
} catch (bytes memory lowLevelData) {
// custom errors and anything else
}try only works with external calls (and contract creation with new), not with internal function calls.
A first example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Divider {
function divide(uint256 a, uint256 b) external pure returns (uint256) {
require(a <= 1000, "a too large");
return a / b;
}
}
contract Main {
Divider private divider = new Divider();
function safeDivide(uint256 a, uint256 b) internal view {
try divider.divide(a, b) returns (uint256 result) {
console.log("result:", result);
} catch Error(string memory reason) {
console.log("Error:", reason);
} catch Panic(uint256 code) {
console.log("Panic code:", code);
}
}
function main() external view {
safeDivide(10, 3);
safeDivide(5000, 1);
safeDivide(10, 0);
console.log("main() kept running");
}
}result: 3
Error: a too large
Panic code: 18
main() kept running
Panic code 18 is 0x12, division by zero.
Catching custom errors
Custom errors arrive in the generic catch (bytes memory data) clause. Compare the first four bytes with the error's selector and decode the arguments:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Lender {
error LimitExceeded(uint256 limit, uint256 requested);
function borrow(uint256 amount) external pure returns (uint256) {
if (amount > 500) revert LimitExceeded(500, amount);
return amount;
}
}
contract Main {
function main() external {
Lender lender = new Lender();
try lender.borrow(800) returns (uint256 got) {
console.log("borrowed", got);
} catch (bytes memory data) {
if (bytes4(data) == Lender.LimitExceeded.selector) {
// skip the 4-byte selector, then decode the arguments
(uint256 limit, uint256 requested) = abi.decode(sliceArgs(data), (uint256, uint256));
console.log("limit", limit, "requested", requested);
} else {
console.log("unknown error");
}
}
}
function sliceArgs(bytes memory data) internal pure returns (bytes memory args) {
args = new bytes(data.length - 4);
for (uint256 i = 4; i < data.length; i++) args[i - 4] = data[i];
}
}limit 500 requested 800
try with new
Contract creation can fail too, for example when a constructor validates its arguments:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Pool {
uint256 public feeBps;
constructor(uint256 feeBps_) {
require(feeBps_ <= 1000, "fee above 10%");
feeBps = feeBps_;
}
}
contract Main {
function tryCreate(uint256 fee) internal {
try new Pool(fee) returns (Pool pool) {
console.log("created pool with fee", pool.feeBps());
} catch Error(string memory reason) {
console.log("could not create:", reason);
}
}
function main() external {
tryCreate(30);
tryCreate(5000);
}
}created pool with fee 30
could not create: fee above 10%
A fallback data source
A practical pattern: ask a primary source, and if it fails, use a backup. One failing dependency no longer breaks your contract.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
interface IPrice {
function price() external view returns (uint256);
}
contract BrokenFeed is IPrice {
function price() external pure returns (uint256) {
revert("feed offline");
}
}
contract BackupFeed is IPrice {
function price() external pure returns (uint256) {
return 1999;
}
}
contract Main {
function readPrice(IPrice primary, IPrice backup) internal view returns (uint256) {
try primary.price() returns (uint256 p) {
return p;
} catch {
console.log("primary failed, using backup");
return backup.price();
}
}
function main() external returns (uint256) {
return readPrice(new BrokenFeed(), new BackupFeed());
}
}primary failed, using backup
main() returned: 1999
A bare catch { … } catches every kind of failure when you don't need the details.
What try/catch does not catch
- Errors inside the
trysuccess block or thecatchblocks themselves: they revert normally. - Calls to an address without code: the compiler's code-size check runs in the caller, before the call, so the revert happens outside the
try. - Return data that cannot be decoded into the declared
returns (...)types. - Running out of gas in the calling function.
State changes made by the failed call are rolled back, but changes your own function made before the try stay. Use try/catch deliberately: often the right reaction to a failed call really is to fail.
Test yourself
Which kind of call can be used with try?
- Internal function calls
- External calls and contract creation
- Library internal functions
- Any expression
A callee does revert InsufficientFunds(10);. Which catch clause receives it?
catch Error(string memory)catch Panic(uint256)catch (bytes memory data)- None; custom errors can't be caught
What panic code is caught when the callee divides by zero?
- 0x01
- 0x11
- 0x12
- 0x32