Learn/Go/9. Handling errors
Lesson 9 of 15
Sign in

Go, lesson 9

Handling errors

Things go wrong: a user types abc where you wanted a number, a file is missing, an account has too little money. Many languages throw exceptions that jump out of your code. Go takes a plainer approach: an error is just a value that a function returns, and you check it.

The error type

error is a built-in interface with one method, Error() string. A function that can fail returns an error as its last result. nil means "no error".

This if err != nil check right after the call is the most common shape in Go code. It keeps the failure handling next to the thing that failed, and the happy path continues un-indented below. Printing an error with Println or %v shows its message.

2 exercises to try what you just read.

Exercise 1

Careful calculator

Press Ctrl Enter or Check to test your code.

Exercise 2

Coffee card

Press Ctrl Enter or Check to test your code.

When there is an error, the other results are usually zero values and should not be used.

Making your own errors

errors.New creates an error with a fixed message. fmt.Errorf builds one with formatting verbs, which is handy for including the bad value:

Sentinel errors and errors.Is

Some errors are worth naming so callers can recognise them. Declare them once at package level; by convention their names start with Err:

Callers compare with errors.Is(err, ErrEmpty). Prefer errors.Is over ==, because it also sees through wrapping.

Wrapping errors

As an error travels up through your functions, each layer can add context. The %w verb in fmt.Errorf wraps the original error inside a new one:

The message now reads like a trail: loading price "x": strconv.Atoi: parsing "x": invalid syntax. And because %w keeps the original inside, errors.Is(err, strconv.ErrSyntax) is still true. (%q prints a string with quotes around it.)

Custom error types

When callers need details, define a type with an Error method. Any type with that method satisfies error:

Go 1.26 added errors.AsType, a generic helper that finds an error of a given type in the chain: if le, ok := errors.AsType[*LimitError](err); ok { ... }. The older errors.As does the same job with a pointer argument.

panic is for bugs

Go also has panic, which stops the program with a stack trace. Indexing past the end of a slice panics, for example. Reserve panic for truly impossible situations, and return an error for anything a user or the outside world can cause.

Further reading

  • Go blog: Error handling and Go
  • Go blog: Working with errors in Go 1.13
  • Package errors
  • A Tour of Go: Errors

Each input line holds a calculation: a number, an operator (+, -, * or /) and a number, separated by spaces. Write a function calc(line string) (int, error) and print the result for each line. When a line is invalid, print error: followed by the error message instead, and carry on with the next line. Use exactly these messages:

  • wrong number of parts (not exactly 3): need 3 parts
  • a number that does not parse: bad number "<text>"
  • division by zero: division by zero
  • any other operator: unknown operator "<op>"

Sample input:

Sample output:

A coffee card starts with a balance of 20 credits. Each input line is a purchase amount. Write buy(balance, cost int) (int, error) that returns the new balance. It must return the sentinel error ErrNoCredit (message not enough credit) when the cost is larger than the balance, and an error with the message invalid cost <n> when the cost is zero or negative.

In main, for each line print ok, balance <b> on success. On failure print refused: <message> and keep the old balance. Use errors.Is to detect ErrNoCredit; when it occurs, also print (top up your card) on the next line.

Sample input:

Sample output:

n, err := strconv.Atoi("12a")
if err != nil {
	fmt.Println("bad number:", err)
	return
}
fmt.Println(n * 2)
func checkAge(age int) error {
	if age < 0 {
		return fmt.Errorf("age %d is negative", age)
	}
	return nil
}
var ErrEmpty = errors.New("cart is empty")
func loadPrice(s string) (int, error) {
	p, err := strconv.Atoi(s)
	if err != nil {
		return 0, fmt.Errorf("loading price %q: %w", s, err)
	}
	return p, nil
}
type LimitError struct {
	Want, Have int
}

func (e *LimitError) Error() string {
	return fmt.Sprintf("want %d but only %d left", e.Want, e.Have)
}
6 * 7
10 / 0
4 x 2
seven + 1
42
error: division by zero
error: unknown operator "x"
error: bad number "seven"
4
5
15
-2
ok, balance 16
ok, balance 11
refused: not enough credit
(top up your card)
refused: invalid cost -2