TL ; DR:
Go has no exceptions. A function that can fail returns an error as its last result. The caller checks it with if err != nil.
func (this *Wallet) spend(amount int) (int, error) {
if amount > this.money {
return 0, errors.New("not enough money")
}
this.money -= amount
return this.money, nil
}
left, err := wallet.spend(80)
if err != nil {
fmt.Println("error:", err)
}
Full lesson:
Some requests can't be done. A wallet with 50 can't spend 80.
The method could return a special value, like -1. But the caller may forget to check it. Then the program goes on with a wrong number.
Many languages throw an exception here. Go doesn't. Its errors are normal values that functions return.
Returning an error
spendreturns two values: the money left and anerror.errors.New("not enough money")makes an error with this message.return 0, errors.New(...)stops the method. So the wallet keeps its money.- When all goes well, the method returns
nilas the error.nilmeans no error.
Checking it
- The caller keeps both results, in
leftanderr. if err != nilruns when something went wrong.- Printing
errshows its message. - Use the other result only when
errisnil.
You met this in the Multiple Returns & Errors lesson with strconv.Atoi. Now your own methods do it too.
Your task
A Wallet starts with 50. Its spend method takes money out and returns what is left.
- In
spend, return 0 and an error whenamountis more thanthis.money. Its message is"not enough money". - In the loop, call
spendand keep both results. - When there is an error, print
error:and the error. Else print what was spent and what is left.
The loop tries to spend 20, then 40, then 30. The errors package is already imported.
Expected output:
spent 20, 30 left
error: not enough money
spent 30, 0 leftFree plan: 30 tutor messages. Premium is unlimited.
