Errors Are Values
Errors Are Values
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:
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:
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:
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:
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: Withdraw From Account
Write withdraw(balance, amount int) (int, error) that returns the new balance after a withdrawal.
Rules:
- If
amountis zero or negative, return an error with the message below - If
amountis greater thanbalance, return an error with the message below - Otherwise, return
balance - amountandnil
The error messages must match these exactly:
amount must be positive
insufficient fundsExamples:
withdraw(100, 30)returns70, nilwithdraw(100, 0)returns0, error("amount must be positive")withdraw(50, 200)returns0, error("insufficient funds")