Saturday, July 11, 2026
The BLOCKCHAIN Page
No Result
View All Result
  • Home
  • Cryptocurrency
  • Blockchain
  • Bitcoin
  • Market & Analysis
  • Altcoins
  • DeFi
  • Ethereum
  • Dogecoin
  • XRP
  • Regulations
  • NFTs
The BLOCKCHAIN Page
No Result
View All Result
Home Ethereum

Solidity 0.6.x features: try/catch statement

by admin
August 21, 2023
in Ethereum
0
Solidity 0.6.x features: try/catch statement
0
SHARES
11
VIEWS
Share on FacebookShare on Twitter



The try/catch syntax introduced in 0.6.0 is arguably the largest leap in error dealing with capabilities in Solidity, since purpose strings for revert and require had been launched in v0.4.22. Each attempt and catch have been reserved key phrases since v0.5.9 and now we are able to use them to deal with failures in exterior perform calls with out rolling again the entire transaction (state modifications within the referred to as perform are nonetheless rolled again, however the ones within the calling perform usually are not).

We’re shifting one step away from the purist “all-or-nothing” method in a transaction lifecycle, which falls wanting sensible behaviour we regularly need.

Dealing with exterior name failures

The attempt/catch assertion lets you react on failed exterior calls and contract creation calls, so you can’t use it for inside perform calls. Observe that to wrap a public perform name throughout the similar contract with attempt/catch, it may be made exterior by calling the perform with this..

The instance under demonstrates how attempt/catch is utilized in a manufacturing facility sample the place contract creation would possibly fail. The next CharitySplitter contract requires a compulsory deal with property _owner in its constructor.

pragma solidity ^0.6.1;

contract CharitySplitter {
    deal with public proprietor;
    constructor (deal with _owner) public {
        require(_owner != deal with(0), "no-owner-provided");
        proprietor = _owner;
    }
}

There’s a manufacturing facility contract — CharitySplitterFactory which is used to create and handle situations of CharitySplitter. Within the manufacturing facility we are able to wrap the new CharitySplitter(charityOwner) in a attempt/catch as a failsafe for when that constructor would possibly fail due to an empty charityOwner being handed.

pragma solidity ^0.6.1;
import "./CharitySplitter.sol";
contract CharitySplitterFactory {
    mapping (deal with => CharitySplitter) public charitySplitters;
    uint public errorCount;
    occasion ErrorHandled(string purpose);
    occasion ErrorNotHandled(bytes purpose);
    perform createCharitySplitter(deal with charityOwner) public {
        attempt new CharitySplitter(charityOwner)
            returns (CharitySplitter newCharitySplitter)
        {
            charitySplitters[msg.sender] = newCharitySplitter;
        } catch {
            errorCount++;
        }
    }
}

Observe that with attempt/catch, solely exceptions taking place contained in the exterior name itself are caught. Errors contained in the expression usually are not caught, for instance if the enter parameter for the new CharitySplitter is itself a part of an inside name, any errors it raises won’t be caught. Pattern demonstrating this behaviour is the modified createCharitySplitter perform. Right here the CharitySplitter constructor enter parameter is retrieved dynamically from one other perform — getCharityOwner. If that perform reverts, on this instance with “revert-required-for-testing”, that won’t be caught within the attempt/catch assertion.

perform createCharitySplitter(deal with _charityOwner) public {
    attempt new CharitySplitter(getCharityOwner(_charityOwner, false))
        returns (CharitySplitter newCharitySplitter)
    {
        charitySplitters[msg.sender] = newCharitySplitter;
    } catch (bytes reminiscence purpose) {
        ...
    }
}
perform getCharityOwner(deal with _charityOwner, bool _toPass)
        inside returns (deal with) {
    require(_toPass, "revert-required-for-testing");
    return _charityOwner;
}

Retrieving the error message

We are able to additional lengthen the attempt/catch logic within the createCharitySplitter perform to retrieve the error message if one was emitted by a failing revert or require and emit it in an occasion. There are two methods to attain this:

1. Utilizing catch Error(string reminiscence purpose)

perform createCharitySplitter(deal with _charityOwner) public {
    attempt new CharitySplitter(_charityOwner) returns (CharitySplitter newCharitySplitter)
    {
        charitySplitters[msg.sender] = newCharitySplitter;
    }
    catch Error(string reminiscence purpose)
    {
        errorCount++;
        CharitySplitter newCharitySplitter = new
            CharitySplitter(msg.sender);
        charitySplitters[msg.sender] = newCharitySplitter;
        // Emitting the error in occasion
        emit ErrorHandled(purpose);
    }
    catch
    {
        errorCount++;
    }
}

Which emits the next occasion on a failed constructor require error:

CharitySplitterFactory.ErrorHandled(
    purpose: 'no-owner-provided' (sort: string)
)

2. Utilizing catch (bytes reminiscence purpose)

perform createCharitySplitter(deal with charityOwner) public {
    attempt new CharitySplitter(charityOwner)
        returns (CharitySplitter newCharitySplitter)
    {
        charitySplitters[msg.sender] = newCharitySplitter;
    }
    catch (bytes reminiscence purpose) {
        errorCount++;
        emit ErrorNotHandled(purpose);
    }
}

Which emits the next occasion on a failed constructor require error:

CharitySplitterFactory.ErrorNotHandled(
  purpose: hex'08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000116e6f2d6f776e65722d70726f7669646564000000000000000000000000000000' (sort: bytes)

The above two strategies for retrieving the error string produce an identical outcome. The distinction is that the second technique doesn’t ABI-decode the error string. The benefit of the second technique is that it’s also executed if ABI decoding the error string fails or if no purpose was offered.

Future plans

There are plans to launch help for error varieties that means we will declare errors in an identical strategy to occasions permitting us to catch completely different sort of errors, for instance:

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



Source link

Tags: 0.6.xFeaturesSoliditystatementtrycatch
admin

admin

Recommended

Goldcoin (GLC) Falls 0.23%, Underperforms the Crypto Market Monday

Goldcoin (GLC) Falls 0.23%, Underperforms the Crypto Market Monday

3 years ago
Ethereum Sees $181M Exchange Outflow, Buying Going On?

Ethereum Sees $181M Exchange Outflow, Buying Going On?

3 years ago

Popular News

  • Protocol-Owned Liquidity: A Sustainable Path for DeFi

    Protocol-Owned Liquidity: A Sustainable Path for DeFi

    0 shares
    Share 0 Tweet 0
  • Cryptocurrency for College: Exploring DeFi Scholarship Models

    0 shares
    Share 0 Tweet 0
  • What are rebase tokens, and how do they work?

    0 shares
    Share 0 Tweet 0
  • What is Velodrome Finance (VELO): why it’s a next-gen AMM

    0 shares
    Share 0 Tweet 0
  • $10 XRP Price Envisioned By Fund Manager As Ripple Mounts Trillion-Dollar Payment Markets ⋆ ZyCrypto

    0 shares
    Share 0 Tweet 0

Latest

SpaceX wants to launch 100,000 more Starlink satellites – for 100x the bandwidth

SpaceX wants to launch 100,000 more Starlink satellites – for 100x the bandwidth

July 10, 2026
I set up a solar panel security camera in my yard – and the image quality beat my Ring

I set up a solar panel security camera in my yard – and the image quality beat my Ring

July 10, 2026

Categories

  • Altcoins
  • Bitcoin
  • Blockchain
  • Cryptocurrency
  • DeFi
  • Dogecoin
  • Ethereum
  • Market & Analysis
  • NFTs & Metaverse
  • Regulations
  • XRP

Follow us

Recommended

  • SpaceX wants to launch 100,000 more Starlink satellites – for 100x the bandwidth
  • I set up a solar panel security camera in my yard – and the image quality beat my Ring
  • LG is giving away free soundbars with this CineBeam Q projector deal – how to qualify
  • ‘I’m not a programmer’ anymore: Linus Torvalds on the only two tools he uses now
  • I replaced my Sonos home theater with this Sony system – here’s why innovation is king
  • About us
  • Privacy Policy
  • Terms & Conditions

© 2023 TheBlockchainPage | All Rights Reserved

No Result
View All Result
  • Home
  • Cryptocurrency
  • Blockchain
  • Bitcoin
  • Market & Analysis
  • Altcoins
  • DeFi
  • Ethereum
  • Dogecoin
  • XRP
  • Regulations
  • NFTs

© 2023 TheBlockchainPage | All Rights Reserved