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;
_to.transfer(_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:
- Deploy a new Instance!
- Copy your address
- Enter an amount
- 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!