• About
  • FAQ
  • Earn Bitcoin while Surfing the net
  • Buy & Sell Crypto on Paxful
Newsletter
Approx Foundation
  • Home
    • Home – Layout 1
  • Bitcoin
  • Ethereum
  • Regulation
  • Market
  • Blockchain
  • Business
  • Guide
  • Contact Us
No Result
View All Result
  • Home
    • Home – Layout 1
  • Bitcoin
  • Ethereum
  • Regulation
  • Market
  • Blockchain
  • Business
  • Guide
  • Contact Us
No Result
View All Result
Approx Foundation
No Result
View All Result
Home Regulation

Solidity 0.6.x features: try/catch statement

Moussa by Moussa
January 13, 2024
in Regulation
0
Solidity 0.6.x features: try/catch statement
189
SHARES
1.5k
VIEWS
Share on FacebookShare on Twitter



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.

Related articles

Landmark $6 billion influx boosts Bitcoin and Ethereum ETFs

Landmark $6 billion influx boosts Bitcoin and Ethereum ETFs

July 1, 2025
DEXs capture almost 30% of CEX spot activity in June, setting new record

DEXs capture almost 30% of CEX spot activity in June, setting new record

June 30, 2025

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

Share76Tweet47

Related Posts

Landmark $6 billion influx boosts Bitcoin and Ethereum ETFs

Landmark $6 billion influx boosts Bitcoin and Ethereum ETFs

by Moussa
July 1, 2025
0

June 2025 was a landmark month for US spot Bitcoin and Ethereum exchange-traded funds (ETFs), as they collectively secured nearly...

DEXs capture almost 30% of CEX spot activity in June, setting new record

DEXs capture almost 30% of CEX spot activity in June, setting new record

by Moussa
June 30, 2025
0

Decentralized exchanges (DEX) processed roughly $385 billion of spot trades in June, equal to almost 30% of the turnover recorded...

German banking giant Sparkassen to offer crypto trading to 50 million customers by 2026

German banking giant Sparkassen to offer crypto trading to 50 million customers by 2026

by Moussa
June 30, 2025
0

Germany’s largest banking group, Sparkassen-Finanzgruppe, is preparing to offer crypto trading services to its retail clients by summer 2026, Bloomberg...

SEC clears Ethereum ETF options trading for BlackRock and Fidelity

Ethereum poised for $3,000 with regulatory tailwinds and ETF demand

by Moussa
June 30, 2025
0

Recent tailwinds such as staking on exchange-traded funds (ETFs) and regulatory clarity may drive Ethereum (ETH) toward $3,000 in the...

Vitalik Buterin says pluralistic ZK digital IDs are the ‘best realistic solution’ to preserve privacy

Vitalik Buterin says pluralistic ZK digital IDs are the ‘best realistic solution’ to preserve privacy

by Moussa
June 29, 2025
0

Ethereum co-founder Vitalik Buterin believes that one-per-person digital ID systems, despite using zero-knowledge proofs (ZK proofs), carry risks to privacy....

Load More

youssufi.com

sephina.com

[vc_row full_width="stretch_row" parallax="content-moving" vc_row_background="" background_repeat="no-repeat" background_position="center center" footer_scheme="dark" css=".vc_custom_1517813231908{padding-top: 60px !important;padding-bottom: 30px !important;background-color: #191818 !important;background-position: center;background-repeat: no-repeat !important;background-size: cover !important;}" footer_widget_title_color="#fcbf46" footer_button_bg="#fcb11e"][vc_column width="1/4"]

We bring you the latest in Crypto News

[/vc_column][vc_column width="1/4"][vc_wp_categories]
[/vc_column][vc_column width="1/4"][vc_wp_tagcloud taxonomy="post_tag"][/vc_column][vc_column width="1/4"]

Newsletter

[vc_raw_html]JTNDcCUzRSUzQ2RpdiUyMGNsYXNzJTNEJTIydG5wJTIwdG5wLXN1YnNjcmlwdGlvbiUyMiUzRSUwQSUzQ2Zvcm0lMjBtZXRob2QlM0QlMjJwb3N0JTIyJTIwYWN0aW9uJTNEJTIyaHR0cHMlM0ElMkYlMkZhcHByb3gub3JnJTJGJTNGbmElM0RzJTIyJTNFJTBBJTBBJTNDaW5wdXQlMjB0eXBlJTNEJTIyaGlkZGVuJTIyJTIwbmFtZSUzRCUyMm5sYW5nJTIyJTIwdmFsdWUlM0QlMjIlMjIlM0UlM0NkaXYlMjBjbGFzcyUzRCUyMnRucC1maWVsZCUyMHRucC1maWVsZC1maXJzdG5hbWUlMjIlM0UlM0NsYWJlbCUyMGZvciUzRCUyMnRucC0xJTIyJTNFRmlyc3QlMjBuYW1lJTIwb3IlMjBmdWxsJTIwbmFtZSUzQyUyRmxhYmVsJTNFJTBBJTNDaW5wdXQlMjBjbGFzcyUzRCUyMnRucC1uYW1lJTIyJTIwdHlwZSUzRCUyMnRleHQlMjIlMjBuYW1lJTNEJTIybm4lMjIlMjBpZCUzRCUyMnRucC0xJTIyJTIwdmFsdWUlM0QlMjIlMjIlM0UlM0MlMkZkaXYlM0UlMEElM0NkaXYlMjBjbGFzcyUzRCUyMnRucC1maWVsZCUyMHRucC1maWVsZC1lbWFpbCUyMiUzRSUzQ2xhYmVsJTIwZm9yJTNEJTIydG5wLTIlMjIlM0VFbWFpbCUzQyUyRmxhYmVsJTNFJTBBJTNDaW5wdXQlMjBjbGFzcyUzRCUyMnRucC1lbWFpbCUyMiUyMHR5cGUlM0QlMjJlbWFpbCUyMiUyMG5hbWUlM0QlMjJuZSUyMiUyMGlkJTNEJTIydG5wLTIlMjIlMjB2YWx1ZSUzRCUyMiUyMiUyMHJlcXVpcmVkJTNFJTNDJTJGZGl2JTNFJTBBJTNDZGl2JTIwY2xhc3MlM0QlMjJ0bnAtZmllbGQlMjB0bnAtcHJpdmFjeS1maWVsZCUyMiUzRSUzQ2xhYmVsJTNFJTNDaW5wdXQlMjB0eXBlJTNEJTIyY2hlY2tib3glMjIlMjBuYW1lJTNEJTIybnklMjIlMjByZXF1aXJlZCUyMGNsYXNzJTNEJTIydG5wLXByaXZhY3klMjIlM0UlQzIlQTBCeSUyMGNvbnRpbnVpbmclMkMlMjB5b3UlMjBhY2NlcHQlMjB0aGUlMjBwcml2YWN5JTIwcG9saWN5JTNDJTJGbGFiZWwlM0UlM0MlMkZkaXYlM0UlM0NkaXYlMjBjbGFzcyUzRCUyMnRucC1maWVsZCUyMHRucC1maWVsZC1idXR0b24lMjIlM0UlM0NpbnB1dCUyMGNsYXNzJTNEJTIydG5wLXN1Ym1pdCUyMiUyMHR5cGUlM0QlMjJzdWJtaXQlMjIlMjB2YWx1ZSUzRCUyMlN1YnNjcmliZSUyMiUyMCUzRSUwQSUzQyUyRmRpdiUzRSUwQSUzQyUyRmZvcm0lM0UlMEElM0MlMkZkaXYlM0UlM0NiciUyRiUzRSUzQyUyRnAlM0U=[/vc_raw_html][/vc_column][/vc_row]
No Result
View All Result
  • Contact Us
  • Homepages
  • Business
  • Guide

© 2024 APPROX FOUNDATION - The Crypto Currency News