Skip to content

Latest commit

 

History

History
35 lines (27 loc) · 1.24 KB

File metadata and controls

35 lines (27 loc) · 1.24 KB

Try-Catch

代码

// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;

contract TryCatch {
    event LogError(string error);

    // try-catch only works in this version or later
    function deposit() external payable {
        emit LogError("Error: Deposit failed.");
        // msg.value is a global variable that contains the amount (in wei) sent with the message
        try this.balance += msg.value {
            // Do something
        } catch Error(string memory reason) {
            // Revert with reason string
            emit LogError(reason);
        } catch {
            // Fallback for other errors
            emit LogError("Unknown error occurred.");
        }
    }
}

描述

Solidity中的try-catch块可用于在发生错误时处理异常。 在这种情况下,合约尝试将发送的以太币存入其余额中。

使用try-catch语句块,可以捕获并处理可能导致存款失败的错误。如果发生错误,则会打印带有错误消息的事件日志,并相应地处理异常。在此示例中,我们定义了两个catch块-一个用于特定类型的错误(即Error),另一个用于所有其他类型的错误。

请注意,try-catch语句仅限于Solidity 0.5.0或更高版本。