Solidity 069 TryCatch

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;

// SimpleDivision contract that performs division of two numbers
contract SimpleDivision {
    // Function to divide two numbers, requires the second number to be greater than 0
    function Divide2Nums(uint256 numone, uint256 numtwo) public pure returns (uint256) {
        // Ensure the divisor is not zero to prevent division by zero error
        require(numtwo > 0, "numtwo is less than or equal to zero");
        // Perform the division and return the result
        return numone / numtwo;
    }
}

// TryCatchExample contract that demonstrates try-catch functionality with SimpleDivision contract
contract TryCatchExample {
    // Instance of the SimpleDivision contract
    SimpleDivision sa;

    // Event to log results of the division and any error messages
    event myevent(uint256 resultOrErrorCode, string message);
    // Event to log low-level error data
    event mybytes(bytes lowLevelData);
    
    // Constructor that initializes a new SimpleDivision contract instance
    constructor() {
        sa = new SimpleDivision();
    }

    // Function to perform division and handle any errors using try-catch
    function GetDivision(uint256 a, uint256 b) public returns (bool) {
        // Try to perform the division using the Divide2Nums function
        try sa.Divide2Nums(a, b) returns (uint256 ab) {
            // If successful, emit the result and a success message
            emit myevent(ab, "pure success");
            return true;
        }
        // Catch block for require statement failures in the called function
        catch Error(string memory reason) {
            // Emit the error reason
            emit myevent(0, reason);
            return false;
        }
        // Catch block for internal errors (like division by zero) that revert the transaction
        catch Panic(uint errorCode) {
            // Emit the error code and a failure message
            emit myevent(errorCode, "pure failure");
            return false;
        }
        // Catch block for other low-level errors
        catch (bytes memory lowLevelData) {
            // Emit the low-level error data
            emit mybytes(lowLevelData);
            return false;
        }
    }
}
 

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值