The bill is $32, and the customer hands over $20. The cashier at Bimo's Meatball Stall doesn't slam the table. They hand back $0 change together with a note: "not enough money". Whoever receives it must read the note first, before trusting the change.
Go handles failure the same way. Nothing is "thrown" and caught with try/catch. A failure is an ordinary value of type error, returned by a function as its last result.
error is an interface
error is a built-in Go interface with one method:
type error interface {
Error() string
}
Any type with Error() string is an error. The value nil means no error. The simplest way to make one: errors.New("not enough money") from the errors package.
The if err != nil pattern
package main
import (
"errors"
"fmt"
"strconv"
)
var ErrNotEnoughMoney = errors.New("not enough money")
func pay(total int, input string) (int, error) {
money, err := strconv.Atoi(input)
if err != nil {
return 0, fmt.Errorf("read money %q: %w", input, err)
}
if money < total {
return 0, fmt.Errorf("pay %d of %d: %w", money, total, ErrNotEnoughMoney)
}
return money - total, nil
}
func main() {
change, err := pay(32, "50")
if err != nil {
fmt.Println("failed:", err)
return
}
fmt.Println("change:", change)
}
strconv.Atoi(input)(packagestrconv, string conversion) turns the text the cashier typed into anint. It returns(int, error): text that isn't a number gives an error.- Every step that can fail is checked straight away:
if err != nil { return ... }. As soon as something is wrong, the function leaves right there with a zero value (0) and the error. If all goes well, the last line returns the result andnil. - In
main, the error is checked beforechangeis used. The error branch prints and thenreturns, so the line after it doesn't run.
input |
err |
Printed |
|---|---|---|
"50" |
nil |
change: 18 |
"32" |
nil |
change: 0 |
"20" |
not enough money | failed: pay 20 of 32: not enough money |
"$50" |
not a number | failed: read money "$50": strconv.Atoi: parsing "$50": invalid syntax |
The same thing in miniature: _, err := strconv.Atoi("abc") fails because "abc" isn't a number, so if err != nil { fmt.Println("error") } prints error.
In the exercise: safeDivide
The function safeDivide(a, b float64) (float64, error) is already in the starter code: if b == 0 it returns errors.New("cannot divide by zero"), otherwise a / b, nil. Your job is in main: receive both results, then check with if err != nil.
3.3333333333333335
Error: cannot divide by zero
safeDivide(10, 3) gives 3.3333333333333335 (that's how a float64 prints 10/3), and safeDivide(10, 0) gives an error whose message is printed.
errors.New or fmt.Errorf
errors.New("not enough money")makes an error with a fixed message. An error that callers will check is usually kept in a package variable starting withErr:var ErrNotEnoughMoney = errors.New("not enough money").fmt.Errorfbuilds the message with verbs likePrintf, so it can add details:pay 20 of 32.- The verb
%w(wrap) wraps the original error inside the new one. The messages are joined, and the original error can still be found.
errors.Is(err, ErrNotEnoughMoney) searches through that wrapping and answers whether ErrNotEnoughMoney is inside:
fmt.Println(errors.Is(err, ErrNotEnoughMoney)) // true with %w, false with %v
With %v, the message is exactly the same, but only the text is copied. The original error is gone, so errors.Is answers false.
📌 errors.As: get the details out of an error
errors.As looks for an error of a given type inside the wrapping, then puts it into a variable:
var numErr *strconv.NumError
if errors.As(err, &numErr) {
fmt.Println(numErr.Func, numErr.Num) // Atoi $50
}
For the input "$50", the error from strconv.Atoi has type *strconv.NumError, so numErr.Num holds the text that couldn't be read. Making your own error types comes in the next lesson, Custom Errors.
Since Go 1.26 there is errors.AsType, a generic version of errors.As. You write the type inside [...], and the result becomes a new variable right away:
if numErr, ok := errors.AsType[*strconv.NumError](err); ok {
fmt.Println(numErr.Func, numErr.Num) // Atoi $50
}
The Go 1.26 release notes say AsType is type-safe, faster and, in most cases, easier to use. Use errors.AsType on Go 1.26 and later. errors.As still works, and you still need it when the code must run on an older Go.
Don't throw errors away with _
Back to the customer who paid $20. This time the error is thrown away with _. Guess: does the program stop with an error, or calmly print change: 0?
change, _ := pay(32, "20")
fmt.Println("change:", change)
change: 0
No error shows up. The program calmly prints change: 0, though the customer hasn't paid in full. An error in Go stops nothing by itself; throw it away and the warning is simply gone.
⚠️ Errors that slip by unnoticed
- Using the result before checking
err. Iferr != nil, the result is just a zero value. Check first, then use it. %vwhen you meant%w. The message is the same, buterrors.Isanderrors.Ascan no longer find the original error.- Comparing message text.
err.Error() == "not enough money"is fragile, and twoerrors.New("not enough money")are not the same error (a == bisfalse). Keep it once inErrNotEnoughMoney, then useerrors.Is. - Receiving
errbut not checking it.money, err := strconv.Atoi(...)without usingerrfails to compile withdeclared and not used: err. That's a sign you forgot to handle it.
TL;DR: An error in Go is a value of type error, an interface with the method Error() string, returned as the last result; nil means no error. The pattern: result, err := f(), then if err != nil { ... return } before the result is used. errors.New makes an error with a fixed message, fmt.Errorf adds details, and %w wraps the original error so errors.Is(err, ErrNotEnoughMoney) and errors.As(err, &numErr) can still find it; %v only copies the text. strconv.Atoi("abc") returns an error. In the exercise, safeDivide(10, 3) prints 3.3333333333333335 and safeDivide(10, 0) prints cannot divide by zero. Don't throw errors away with _.
⚡ An error is an ordinary value
Write:
change, err := pay(32, "50")
if err != nil {
fmt.Println("failed:", err)
return
}
fmt.Println("change:", change)
Meaning: Go has no try/catch. A function that can fail returns an error as its last result, and the caller checks if err != nil before using the result. nil means no error.
⚡ Making your own error
Write:
var ErrNotEnoughMoney = errors.New("not enough money")
return 0, fmt.Errorf("pay %d of %d: %w", money, total, ErrNotEnoughMoney)
Meaning: errors.New makes an error with a fixed message. fmt.Errorf with %w adds details and wraps the original error, so errors.Is(err, ErrNotEnoughMoney) can still find it.
⚡ Don't throw errors away
Guess first: change, _ := pay(32, "20"). Does the program stop with an error?
No. The program calmly prints change: 0, though the customer hasn't paid in full. An error in Go stops nothing by itself.
Meaning: An error thrown away with _ is a warning that is simply gone.