Close Menu
Altcoin ObserverAltcoin Observer
  • Regulation
  • Bitcoin
  • Altcoins
  • Market
  • Analysis
  • DeFi
  • Security
  • Ethereum
Categories
  • Altcoins (1,149)
  • Analysis (1,351)
  • Bitcoin (1,924)
  • Blockchain (1,114)
  • DeFi (1,322)
  • Ethereum (1,317)
  • Event (48)
  • Exclusive Deep Dive (1)
  • Landscape Ads (2)
  • Market (1,362)
  • Reddit (576)
  • Regulation (1,268)
  • Security (1,819)
  • Thought Leadership (1)
  • Uncategorized (3)
  • Videos (39)
Hand picked
  • What’s the most reliable crypto DeFi wallet in 2025?
  • Coinbase Revenue from XRP Tops ETH, Sol AS Holdings Saar 458% – Is the XRP price ready for the break?
  • The CEO of cryptochus says it is time to throw the “cycle theory”
  • Meta Exploration of Stablecoin payments for its products: report
  • Lyon, France – Interpol’s new opinion is Silver (Part 2 of 3: The United States softens its mechanism for applying cryptography) | Is Law, pa
We are social
  • Facebook
  • Twitter
  • Instagram
  • YouTube
Facebook X (Twitter) Instagram
  • About us
  • Disclaimer
  • Terms of service
  • Privacy policy
  • Contact us
Facebook X (Twitter) Instagram YouTube LinkedIn
Altcoin ObserverAltcoin Observer
  • Regulation
  • Bitcoin
  • Altcoins
  • Market
  • Analysis
  • DeFi
  • Security
  • Ethereum
Events
Altcoin ObserverAltcoin Observer
Home»Ethereum»Solidity 0.6.x features: try/catch statement
Ethereum

Solidity 0.6.x features: try/catch statement

January 3, 2025No Comments4 Mins Read
Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
Solidity Logo.svg .svgxml
Share
Facebook Twitter LinkedIn Pinterest Email



THE try/catch syntax introduced in version 0.6.0 is arguably the biggest advancement in error handling capabilities in Solidity, since reason chains for to come back And require were released in v0.4.22. Both to 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 entire transaction (state changes in the called function are always rolled back, but those in the calling function are not).

We’re moving further away from the purist “all or nothing” approach to the transaction lifecycle, which falls far short of the practical behaviors we often desire.

Managing failed external calls

The try/catch statement allows you to react in case of failure external calls and contract creation calls, so you cannot use it to internal function calls. Note that to wrap a public function call in the same contract with try/catch, it can be made external by calling the function with This..

The example below shows how try/catch is used in a factory pattern where contract creation may fail. What follows CharitySplitter contract requires 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 factory, we can pack the new CharitySplitter (charityOwner) in a try/catch as a safety when this constructor might fail due to a void CharityOwner being adopted.

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 occurring inside the outer call itself are caught. Errors inside the expression are not detected, for example if the input parameter for the new CharitySplitter is itself part of an internal call, errors it generates will not be detected. The example demonstrating this behavior is the modified model createCharitySplitter function. Here the CharitySplitter constructor input parameter is dynamically retrieved from another function – getCharityOwner. If this function returns, in this example with “return-required-for-testing”which will not be captured 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 it was issued by a failure to come back Or require and broadcast it during an event. There are two ways to achieve this:

1. Use Capture 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 failing constructor requires an error:

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

2. Use catch (memory reason in bytes)

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 failing constructor requires an 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 the ABI decoding of the error string fails or no reason was provided.

Future projects

There are plans to release support for error types, meaning we will be able to declare errors in the same way as events allowing us to detect different error types, for example:

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



Source link

Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
Previous ArticlePepe Unchained price increases by 20% during Pump Pad launch
Next Article Blockchain works with drone swarms, researchers say

Related Posts

Ethereum

Ethereum breaks the parable with a multi -year drop in Bitcoin – Haussier inversion?

May 10, 2025
Ethereum

Ethereum breaks key resistance in a massive movement – Higher High confirms the momentum

May 10, 2025
Ethereum

Blackrock meeting dry crypto task force to discuss tokenization, rules andp

May 10, 2025
Add A Comment
Leave A Reply Cancel Reply

Single Page Post
Share
  • Facebook
  • Twitter
  • Instagram
  • YouTube
Featured Content
Videos

Tokenomics : The Mechanics and Magic of Decentralized Funding | Jason Fernandes | TEDxSDMIMD Mysuru

May 9, 2025

The Mechanics and Magic of Decentralized Funding explores the powerful intersection of blockchain technology, economic…

Event

Altcoin Observer – Official Media Partner for Dutch Blockchain Week 2025

May 9, 2025

30% off DBW Summit! Use code OBSERVER30 at dutchblockchainweek.com. Only for A.O and AdLunam Community …

1 2 3 … 44 Next
  • Facebook
  • Twitter
  • Instagram
  • YouTube

Coinbase Revenue from XRP Tops ETH, Sol AS Holdings Saar 458% – Is the XRP price ready for the break?

May 10, 2025

Pepe Price jumps 45% powered by Ethereum Rally

May 10, 2025

XRP for health care: Welgistics secures $ 50 million in credit for pioneer blockchain payments

May 10, 2025
Facebook X (Twitter) Instagram LinkedIn
  • About us
  • Disclaimer
  • Terms of service
  • Privacy policy
  • Contact us
© 2025 Altcoin Observer. all rights reserved by Tech Team.

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

bitcoin
Bitcoin (BTC) $ 103,555.75
ethereum
Ethereum (ETH) $ 2,376.73
tether
Tether (USDT) $ 1.00
xrp
XRP (XRP) $ 2.38
bnb
BNB (BNB) $ 658.56
solana
Solana (SOL) $ 171.65
usd-coin
USDC (USDC) $ 1.00
dogecoin
Dogecoin (DOGE) $ 0.223014
cardano
Cardano (ADA) $ 0.79191
tron
TRON (TRX) $ 0.263799