Start learning free

LESSON 613 OF 639 · OBJECT-ORIENTED PROGRAMMING

Errors and Exceptions in Go in Go

Lesson

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

  • spend returns two values: the money left and an error.
  • 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 nil as the error. nil means no error.

Checking it

  • The caller keeps both results, in left and err.
  • if err != nil runs when something went wrong.
  • Printing err shows its message.
  • Use the other result only when err is nil.

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 when amount is more than this.money. Its message is "not enough money".
  • In the loop, call spend and 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 left
STEP 1 OF 4
    Ctrl + Enter to check

    Raising Errors in Go

    Keep going with Go500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free