Errors Are Values

Errors Are Values

Errors Are Values

example.go
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("cannot divide by zero")
    }
    return a / b, nil
}

No try/catch. No hidden surprises. In Go, errors are just values returned from functions.

The two most common ways to create an error are:

example.go
errors.New("cannot divide by zero")
fmt.Errorf("invalid value: %d", num)

errors.New takes a plain string. fmt.Errorf lets you format values into the message, which makes it more flexible. When everything is fine, return nil instead, which means "no error."

Both live in the standard library, so remember to import them. errors.New needs "errors", and fmt.Errorf needs "fmt".

When you import more than one package, use the grouped form with each package on its own line:

example.go
import (
    "errors"
    "fmt"
)

Writing import ("errors" "fmt") on a single line is a syntax error. Each package gets its own line between the parentheses.

Don't name a variable error

error is a built-in type in Go. If you name a variable error, you shadow the type and get confusing compile errors further down. Use err for the value:

example.go
result, err := withdraw(100, 30) // good
result, error := withdraw(100, 30) // avoid, shadows the type

Last lesson you used a bool to signal failure. That tells you something went wrong, but not what. Errors tell you why:

example.go
result, err := divide(10, 0)
if err != nil {
    fmt.Println(err) // "cannot divide by zero"
}

A function that can fail returns an error as its last value. The caller checks it with if err != nil.

>_Exercise

Exercise: Withdraw From Account

Write withdraw(balance, amount int) (int, error) that returns the new balance after a withdrawal.

Rules:

  • If amount is zero or negative, return an error with the message below
  • If amount is greater than balance, return an error with the message below
  • Otherwise, return balance - amount and nil

The error messages must match these exactly:

example.go
amount must be positive
insufficient funds

Examples:

  • withdraw(100, 30) returns 70, nil
  • withdraw(100, 0) returns 0, error("amount must be positive")
  • withdraw(50, 200) returns 0, error("insufficient funds")
Stuck? Reveal a hint to help you.
Hints (0/5)
Key Takeaway
Next UpThe full type lineup: sized integers, bytes, and runes.