Skip to content

Add a Require

Alright, now it's time to add a require instead of the if/else control structure. Did you try? Let's compare our code:

//SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

contract ExceptionExample {

    mapping(address => uint) public balanceReceived;

    function receiveMoney() public payable {
        balanceReceived[msg.sender] += msg.value;

    function withdrawMoney(address payable _to, uint _amount) public {
        require(_amount <= balanceReceived[msg.sender], "Not Enough Funds, aborting");

        balanceReceived[msg.sender] -= _amount;

If you run this now and try to withdraw more Ether than you have, it will output an error. Repeat the steps from before:

  1. Deploy a new Instance!
  2. Copy your address
  3. Enter an amount
  4. Click on "withdrawMoney"

Observe the log window:

How cool is that! Not only your transaction fails, which is what we want, we also get proper feedback to the user. Great! But if we have require statements, what are assert for?

Let's check it out!

Last update: March 28, 2022