Solidity Steps
  • Learning Solidity
  • Step 1
    • 1: Introduction
    • 2: Data Types
    • 3: Functions
    • 4: Control Structures
    • 5: State Variable
    • 6: Local Variables
    • 7: Global Variables
    • 8: View Keyword
    • 9: Pure Keyword
  • STEP 2
    • 10: Immunable Keyword
    • 11: Events
    • 12: Condition
    • 13: While Loop
    • 14: Do While Loop
    • 15: For Loop
    • 16: Required
    • 17: Assert
    • 18: Revert
    • 19: Modifier
  • STEP 3
    • 20: Constructor
    • 21: Mapping
    • 22: Array
    • 23: Enum
    • 24: Structs
    • 25: Data Location
    • 26: Inheritance
    • 27: The Shadowing Effect
    • 28: Super Keyword
    • 29: Visibility
  • STEP 4
    • 30: Interface
    • 31: Abstract Contract
    • 32: Payable
    • 33: Using type()
    • 34: Sending Ether
    • 35: Receive
    • 36: Fallback
    • 37: Call
    • 38: DelegateCall
    • 39: Calling Other Contracts
  • STEP 5
    • 40: Factory Contract
    • 41: Proxy Contract
    • 42: Create2
    • 43: Try and Catch
    • 44: Solidity Library
    • 45: ABI Encoded
    • 46: ABI Decoded
    • 47: Keccak256
    • 48: Function Signature Hash
  • TIPS
    • Tips: Solidity by "Immunable"
    • Tips: Truffle Tutorial
    • Tips: Microblog Dapp
    • Tips: Reentrancy
    • Tips: Slither Tutorial
    • Tips: Remix Tutorial
    • Tips: Hardhat Tutorial
  • CAREER
    • 💲Cover Letter
    • 💲Resume
  • ABOUT
    • Contact me
Powered by GitBook
On this page
  1. STEP 5

43: Try and Catch

In Solidity try and catch can be used to handle exceptions. This can prevent a transaction from failing due to an invalid input or a bug in the code.

  • Example 1 In the following example, we want to prevent someone from sending more than 5 ether in a single transaction.

function sendMoney(address _to, uint256 _amount) public payable {    
    try {        
        require(_amount <= 5 ether);        
        _to.transfer(_amount);    
    } 
    catch (bytes32 err) {        
        revert("Only 5 ether can be sent at a time");    
    }
}

In this example, if the _amount is greater than 5 ether, the require statement will throw an exception and the catch block will handle the exception, reverting the transaction and sending a message to the sender.

  • Example 2 In this example, we want to ensure that the sender and receiver are not the same address.

function sendMoney(address _to, uint256 _amount) public payable {    
    try {        
        require(_to != msg.sender);        
        _to.transfer(_amount);    
    } 
    catch (bytes32 err) {        
        revert("Sender and receiver cannot be the same address");    
    }
}

If the sender and receiver are the same address, the require statement will throw an exception and the catch block will handle the exception, reverting the transaction and sending a message to the sender.

That's it for the lesson 43! In the next lesson, Library

Previous42: Create2Next44: Solidity Library

Last updated 1 year ago