Close Menu

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    What's Hot

    UK crypto rules signal major shift: but will they deliver?

    May 16, 2025

    Pi Network slide continues as major announcement underwhelms traders

    May 16, 2025

    LIBRA case judge orders full disclosure of Javier Milei bank accounts

    May 16, 2025
    Facebook X (Twitter) Instagram
    Ai Crypto TimesAi Crypto Times
    • Altcoins
      • Bitcoin
      • Coinbase
      • Litecoin
    • Blockchain
    • Crypto
    • Ethereum
    • Lithosphere News Releases
    X (Twitter) Instagram YouTube LinkedIn
    Ai Crypto TimesAi Crypto Times
    Home » Solidity 0.6.x features: try/catch statement

    Solidity 0.6.x features: try/catch statement

    Michael JohnsonBy Michael JohnsonApril 28, 2025No Comments4 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Share
    Facebook Twitter LinkedIn Pinterest Email



    The try/catch syntax introduced in 0.6.0 is arguably the biggest leap in error handling capabilities in Solidity, since reason strings for revert and require were released in v0.4.22. Both try and catch have been reserved keywords since v0.5.9 and now we can use them to handle failures in external function calls without rolling back the complete transaction (state changes in the called function are still rolled back, but the ones in the calling function are not).

    We are moving one step away from the purist “all-or-nothing” approach in a transaction lifecycle, which falls short of practical behaviour we often want.

    Handling external call failures

    The try/catch statement allows you to react on failed external calls and contract creation calls, so you cannot use it for internal function calls. Note that to wrap a public function call within the same contract with try/catch, it can be made external by calling the function with this..

    The example below demonstrates how try/catch is used in a factory pattern where contract creation might fail. The following CharitySplitter contract requires a mandatory address property _owner in its constructor.

    pragma solidity ^0.6.1;
    
    contract CharitySplitter {
        address public owner;
        constructor (address _owner) public {
            require(_owner != address(0), "no-owner-provided");
            owner = _owner;
        }
    }
    

    There is a factory contract — CharitySplitterFactory which is used to create and manage instances of CharitySplitter. In the factory we can wrap the new CharitySplitter(charityOwner) in a try/catch as a failsafe for when that constructor might fail because of an empty charityOwner being passed.

    pragma solidity ^0.6.1;
    import "./CharitySplitter.sol";
    contract CharitySplitterFactory {
        mapping (address => CharitySplitter) public charitySplitters;
        uint public errorCount;
        event ErrorHandled(string reason);
        event ErrorNotHandled(bytes reason);
        function createCharitySplitter(address charityOwner) public {
            try new CharitySplitter(charityOwner)
                returns (CharitySplitter newCharitySplitter)
            {
                charitySplitters[msg.sender] = newCharitySplitter;
            } catch {
                errorCount++;
            }
        }
    }
    

    Note that with try/catch, only exceptions happening inside the external call itself are caught. Errors inside the expression are not caught, for example if the input parameter for the new CharitySplitter is itself part of an internal call, any errors it raises will not be caught. Sample demonstrating this behaviour is the modified createCharitySplitter function. Here the CharitySplitter constructor input parameter is retrieved dynamically from another function — getCharityOwner. If that function reverts, in this example with “revert-required-for-testing”, that will not be caught in the try/catch statement.

    function createCharitySplitter(address _charityOwner) public {
        try new CharitySplitter(getCharityOwner(_charityOwner, false))
            returns (CharitySplitter newCharitySplitter)
        {
            charitySplitters[msg.sender] = newCharitySplitter;
        } catch (bytes memory reason) {
            ...
        }
    }
    function getCharityOwner(address _charityOwner, bool _toPass)
            internal returns (address) {
        require(_toPass, "revert-required-for-testing");
        return _charityOwner;
    }
    

    Retrieving the error message

    We can further extend the try/catch logic in the createCharitySplitter function to retrieve the error message if one was emitted by a failing revert or require and emit it in an event. There are two ways to achieve this:

    1. Using catch Error(string memory reason)

    function createCharitySplitter(address _charityOwner) public {
        try new CharitySplitter(_charityOwner) returns (CharitySplitter newCharitySplitter)
        {
            charitySplitters[msg.sender] = newCharitySplitter;
        }
        catch Error(string memory reason)
        {
            errorCount++;
            CharitySplitter newCharitySplitter = new
                CharitySplitter(msg.sender);
            charitySplitters[msg.sender] = newCharitySplitter;
            // Emitting the error in event
            emit ErrorHandled(reason);
        }
        catch
        {
            errorCount++;
        }
    }
    

    Which emits the following event on a failed constructor require error:

    CharitySplitterFactory.ErrorHandled(
        reason: 'no-owner-provided' (type: string)
    )
    

    2. Using catch (bytes memory reason)

    function createCharitySplitter(address charityOwner) public {
        try new CharitySplitter(charityOwner)
            returns (CharitySplitter newCharitySplitter)
        {
            charitySplitters[msg.sender] = newCharitySplitter;
        }
        catch (bytes memory reason) {
            errorCount++;
            emit ErrorNotHandled(reason);
        }
    }
    

    Which emits the following event on a failed constructor require error:

    CharitySplitterFactory.ErrorNotHandled(
      reason: hex'08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000116e6f2d6f776e65722d70726f7669646564000000000000000000000000000000' (type: bytes)
    

    The above two methods for retrieving the error string produce a similar result. The difference is that the second method does not ABI-decode the error string. The advantage of the second method is that it is also executed if ABI decoding the error string fails or if no reason was provided.

    Future plans

    There are plans to release support for error types meaning we will be able to declare errors in a similar way to events allowing us to catch different type of errors, for example:

    catch CustomErrorA(uint data1) { … }
    catch CustomErrorB(uint[] memory data2) { … }
    catch {}
    



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Michael Johnson

    Related Posts

    Bitwise CIO bats for diversified crypto investment, compares Bitcoin to Google

    May 14, 2025

    V1.0 Announcing the Trillion Dollar Security Initiative

    May 14, 2025

    Ethereum (ETH) sees major uptick as Pectra upgrade goes live

    May 8, 2025
    Leave A Reply Cancel Reply

    Don't Miss

    UK crypto rules signal major shift: but will they deliver?

    Crypto May 16, 2025

    My wife was born in the United Kingdom and we’ve spent a lot of time…

    Pi Network slide continues as major announcement underwhelms traders

    May 16, 2025

    LIBRA case judge orders full disclosure of Javier Milei bank accounts

    May 16, 2025

    Webull taps Coinbase for crypto custody, trading, and staking

    May 16, 2025
    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Our Picks

    Atua AI Refines Multichain Operations for Enterprise Adaptability

    May 16, 2025

    Colle AI Optimizes Bitcoin Utility to Improve Multichain NFT Distribution

    May 16, 2025

    AGII Deploys Smart Detection Models for On-Chain Infrastructure Resilience

    May 16, 2025

    AGII Enhances Contract Speed With Lightweight Autonomous Logic

    May 16, 2025

    Subscribe to Updates

    Get the latest creative news from SmartMag about art & design.

    Demo
    • Popular
    • Recent
    • Top Reviews

    30 Minutes of Exercise vs 100 Steps a Day: Which One is Better?

    May 16, 2021

    Quisque consectetur libero elit

    September 1, 2020

    Winter Fitness: These Poses Can Keep You Warm

    January 14, 2021

    UK crypto rules signal major shift: but will they deliver?

    May 16, 2025

    Pi Network slide continues as major announcement underwhelms traders

    May 16, 2025

    LIBRA case judge orders full disclosure of Javier Milei bank accounts

    May 16, 2025
    9.3

    Facilisis tincidunt justo eget urna leo dapibus at

    December 19, 2020
    8.9

    Review: Denmark Proposes Corona Pass Mandate for Workers

    January 9, 2020
    8.9

    Laoreet Sed: Suscipit nec dapibus at elit

    December 19, 2020
    Latest Galleries
    [latest_gallery cat="all" number="5" type="slider"]
    Latest Reviews
    8.5

    Review: How Research Could Help with Spinal Cord Injuries

    March 14, 2021
    8.9

    Review: How AI in Soccer could Predict Injuries?

    January 15, 2021
    8.9

    Review: Can Wisconsin Clinch the Big Ten West this Weekend

    January 15, 2021
    Demo
    Top Posts

    Atua AI Extends Bitcoin-Backed Infrastructure for Intelligent Enterprise Operations

    April 23, 202513 Views

    AGII Launches AI-Powered Web3 App To Advance Real-Time Decentralized Infrastructure

    April 26, 20251 Views

    Atua AI Refines Multichain Operations for Enterprise Adaptability

    May 16, 20250 Views

    Colle AI Optimizes Bitcoin Utility to Improve Multichain NFT Distribution

    May 16, 20250 Views
    Don't Miss

    UK crypto rules signal major shift: but will they deliver?

    Crypto May 16, 2025

    My wife was born in the United Kingdom and we’ve spent a lot of time…

    Pi Network slide continues as major announcement underwhelms traders

    May 16, 2025

    LIBRA case judge orders full disclosure of Javier Milei bank accounts

    May 16, 2025

    Webull taps Coinbase for crypto custody, trading, and staking

    May 16, 2025
    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo

    Subscribe to Updates

    Get the latest creative news from SmartMag about art & design.

    Demo
    Top Posts

    Atua AI Extends Bitcoin-Backed Infrastructure for Intelligent Enterprise Operations

    April 23, 202513 Views

    AGII Launches AI-Powered Web3 App To Advance Real-Time Decentralized Infrastructure

    April 26, 20251 Views

    UK crypto rules signal major shift: but will they deliver?

    May 16, 20250 Views

    Pi Network slide continues as major announcement underwhelms traders

    May 16, 20250 Views
    Don't Miss

    UK crypto rules signal major shift: but will they deliver?

    Crypto May 16, 2025

    My wife was born in the United Kingdom and we’ve spent a lot of time…

    Pi Network slide continues as major announcement underwhelms traders

    May 16, 2025

    LIBRA case judge orders full disclosure of Javier Milei bank accounts

    May 16, 2025

    Webull taps Coinbase for crypto custody, trading, and staking

    May 16, 2025
    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo

    Subscribe to Updates

    Get the latest creative news from SmartMag about art & design.

    X (Twitter) Instagram YouTube LinkedIn
    Our Picks

    UK crypto rules signal major shift: but will they deliver?

    May 16, 2025

    Pi Network slide continues as major announcement underwhelms traders

    May 16, 2025

    LIBRA case judge orders full disclosure of Javier Milei bank accounts

    May 16, 2025
    Recent Posts
    • UK crypto rules signal major shift: but will they deliver?
    • Pi Network slide continues as major announcement underwhelms traders
    • LIBRA case judge orders full disclosure of Javier Milei bank accounts
    • Webull taps Coinbase for crypto custody, trading, and staking
    • Inspired by Saylor’s Strategy, TopWin shifts to digital assets by rebranding to ‘AsiaStrategy’
    © 2025 - 2026

    Type above and press Enter to search. Press Esc to cancel.