Executive Summary & Direct Answer

External calls are one of the most failure-prone parts of a Solidity system. A token transfer can revert, a price oracle can be paused, or a downstream contract can return malformed data. Without careful handling, a single failed call can unwind an otherwise valid transaction.

Solidity’s try/catch statement gives you structured control over these failures. It is especially useful when your contract depends on external contracts, factory deployments, or low-level workflows where you want to distinguish between a revert, a panic, and a successful call that still returns unexpected data.

Why try/catch matters

Most Solidity code is written under the assumption that called contracts behave correctly. In practice, that assumption fails often:

  • A third-party contract may revert with a custom error.
  • A function may run out of gas or hit a panic condition.
  • A contract creation may fail because constructor logic reverts.
  • A call may succeed at the EVM level but still return data that cannot be decoded.

If you use a plain external call, any revert bubbles up and aborts the whole transaction. That is sometimes correct, but not always. try/catch lets you isolate failure handling and implement fallback behavior, logging, retries, or partial progress.

Where try/catch can be used

try/catch works only with external calls and contract creation. You cannot use it for internal function calls because those are compiled into direct jumps, not external message calls.

Typical targets include:

  • someContract.someFunction(...)
  • new SomeContract(...)
  • interface calls to external contracts

It is most useful when the caller wants to continue execution after a failure, or when the failure needs to be translated into a more domain-specific response.

Syntax overview

A try block is followed by one or more catch clauses:

try externalCall(...) returns (ReturnType value) {
    // success path
} catch Error(string memory reason) {
    // revert(string) from the callee
} catch Panic(uint256 code) {
    // panic codes such as overflow, division by zero, assert failure
} catch (bytes memory lowLevelData) {
    // everything else, including custom errors
}

You can also catch constructor failures:

try new SomeContract(arg1, arg2) returns (SomeContract instance) {
    // deployment succeeded
} catch {
    // deployment failed
}

Practical example: calling a price oracle safely

A common use case is reading from an oracle that may be temporarily unavailable. In a trading or lending protocol, you may want to fail gracefully, use a cached value, or pause an operation rather than reverting the entire user flow.

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

interface IPriceOracle {
    function latestPrice() external view returns (uint256);
}

contract OracleConsumer {
    IPriceOracle public oracle;
    uint256 public cachedPrice;
    uint256 public lastGoodUpdate;

    event PriceUpdated(uint256 price);
    event OracleFailed(bytes data);

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

    function refreshPrice() external {
        try oracle.latestPrice() returns (uint256 price) {
            require(price > 0, "invalid price");
            cachedPrice = price;
            lastGoodUpdate = block.timestamp;
            emit PriceUpdated(price);
        } catch Error(string memory reason) {
            emit OracleFailed(bytes(reason));
        } catch Panic(uint256 code) {
            emit OracleFailed(abi.encodePacked(code));
        } catch (bytes memory data) {
            emit OracleFailed(data);
        }
    }

    function getPrice() external view returns (uint256) {
        return cachedPrice;
    }
}

This pattern does three useful things:

  1. It preserves the last known good value.
  2. It records the reason for failure.
  3. It avoids a hard revert when the oracle is temporarily broken.

In a production system, you would likely add staleness checks and a maximum age for cachedPrice.

Understanding the different catch clauses

Solidity distinguishes between several failure types. Choosing the right catch clause helps you preserve useful diagnostics.

Catch clauseWhat it capturesTypical source
catch Error(string memory reason)Standard revert stringsrequire(...), revert("...")
catch Panic(uint256 code)Solidity panicsOverflow, division by zero, invalid array access, failed assert
catch (bytes memory data)Anything elseCustom errors, malformed return data, unknown revert payloads

catch Error(string memory reason)

Use this when the callee uses human-readable revert strings. It is convenient for logging and debugging, but it does not cover custom errors.

catch Panic(uint256 code)

This is useful when you want to detect programmer errors or invariant violations in the callee. For example, a panic code may indicate an arithmetic issue or an out-of-bounds access.

catch (bytes memory data)

This is the most general form. It catches custom errors and any revert payload that does not match the other two patterns. In modern Solidity code, this clause is essential because many contracts now prefer custom errors over revert strings.

Handling custom errors from external contracts

Custom errors are efficient, but they are not decoded by catch Error(string memory). If the callee uses custom errors, they will usually end up in the generic catch (bytes memory data) branch.

You can still inspect the raw bytes, emit them, or decode them if you know the error type. For example:

error NotAuthorized(address caller);

interface IRestricted {
    function restrictedAction() external;
}

contract Caller {
    event CallFailed(bytes data);

    function callRestricted(address target) external {
        try IRestricted(target).restrictedAction() {
            // success
        } catch (bytes memory data) {
            emit CallFailed(data);
        }
    }
}

If you control both contracts, you can standardize on a shared error interface and decode the selector off-chain or in a higher-level contract. In many cases, logging the raw revert data is enough for observability.

When try/catch is the right tool

Use try/catch when failure is expected and recoverable. Good examples include:

  • Reading from optional external services
  • Interacting with third-party adapters
  • Deploying helper contracts that may fail under certain conditions
  • Implementing best-effort workflows, such as batch processing
  • Wrapping external calls to produce clearer domain-specific errors

It is less appropriate when failure should always abort the transaction. If a downstream call is mandatory for correctness, a plain external call may be simpler and safer.

Best practices for robust error handling

1. Keep the success path small

The try block should contain only the external call and minimal success handling. Do not put unrelated logic inside it.

2. Avoid swallowing critical failures silently

A catch block that does nothing can hide serious problems. If you intentionally ignore a failure, document why and emit an event if possible.

3. Prefer explicit fallback behavior

If you are using a cached value, fallback route, or degraded mode, make that behavior obvious in the code and in the contract’s public API.

4. Log enough context

Emit events with the target address, failure type, and any useful data. This makes operational debugging much easier.

5. Be careful with state changes before the call

If you update state before the external call and then handle failure in catch, make sure the state remains consistent. Consider whether the state should be updated only after success.

6. Do not assume all failures are recoverable

A panic may indicate a bug in the callee, not a transient runtime issue. Decide whether your contract should retry, pause, or escalate.

A batch-processing pattern

try/catch is particularly useful in batch workflows where one failure should not block the rest of the batch. For example, a registry may need to notify multiple external contracts, but some recipients may be offline or incompatible.

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

interface ISubscriber {
    function notify(uint256 value) external;
}

contract Notifier {
    event Notified(address indexed subscriber, uint256 value);
    event NotificationFailed(address indexed subscriber, bytes data);

    function notifyMany(address[] calldata subscribers, uint256 value) external {
        for (uint256 i = 0; i < subscribers.length; i++) {
            address subscriber = subscribers[i];

            try ISubscriber(subscriber).notify(value) {
                emit Notified(subscriber, value);
            } catch (bytes memory data) {
                emit NotificationFailed(subscriber, data);
            }
        }
    }
}

This approach is useful when partial success is acceptable. It is not suitable for financial operations that require atomicity across all recipients unless you explicitly want best-effort semantics.

Constructor calls and deployment failures

You can also use try/catch around contract creation. This is helpful in factory patterns where the constructor may validate parameters, initialize external dependencies, or enforce role checks.

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

contract Child {
    constructor(uint256 x) {
        require(x > 10, "x too small");
    }
}

contract Factory {
    event ChildCreated(address child);
    event ChildFailed(bytes data);

    function deploy(uint256 x) external returns (address) {
        try new Child(x) returns (Child child) {
            emit ChildCreated(address(child));
            return address(child);
        } catch Error(string memory reason) {
            emit ChildFailed(bytes(reason));
            return address(0);
        } catch (bytes memory data) {
            emit ChildFailed(data);
            return address(0);
        }
    }
}

This pattern is useful when deployment is optional or when the factory should continue operating even if one child instance cannot be created.

Common pitfalls

Catching too broadly

A generic catch (bytes memory data) is powerful, but if you use it everywhere, you may lose important distinctions between expected and unexpected failures.

Ignoring return values

A successful call does not always mean the result is valid. Always validate returned data before using it.

Using try/catch for internal logic

It will not work for internal function calls. If you need structured error handling inside your own contract, use require, revert, and custom errors instead.

Assuming all external calls are safe to continue after failure

If the external call was part of a critical invariant, continuing execution may leave your contract in a broken state. Only recover when the business logic supports it.

Design checklist

Before using try/catch, ask:

  • Is the external call optional or recoverable?
  • Should the transaction continue after failure?
  • Do I need to distinguish between revert strings, panics, and custom errors?
  • What state should be preserved if the call fails?
  • Should I emit an event or expose a fallback value?

If the answer to these questions is clear, try/catch can make your contract significantly more resilient.

Conclusion

try/catch is a practical tool for building contracts that interact with unreliable external systems. It gives you structured failure handling without forcing every error to become a full transaction revert. Used carefully, it improves resilience, observability, and user experience.

The key is to treat it as a design tool, not a way to hide problems. Use it when failure is expected and recoverable, and keep the fallback behavior explicit, auditable, and minimal.

Learn more with useful resources