Bitpath

Lesson 2 · Unit 02

Errors

Return them, check them, wrap them, and save panic for bugs.

13 exercisesabout 3 min

What you practise

  • error is a value you return, if err != nil, wrapping with %w, errors.Is and errors.As, defer, panic and recover and when not to

Try a question from this lesson

Pick one

In Python, int("12a") raises an exception. Go's strconv.Atoi returns two results instead. What prints?

Go
n, err := strconv.Atoi("12a")
fmt.Println(n, err != nil)

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

An error is a value

Go has no exceptions for ordinary failures. A function that can fail returns an error as its last result, and nil means it worked. error is an interface with one method, Error() string.

The caller checks straight away with if err != nil. It is repetitive on purpose: every place something can fail is visible in the code, and nothing jumps up the stack behind your back.

Go
n, err := strconv.Atoi("42")
if err != nil {
  fmt.Println("bad number:", err)
  return
}
fmt.Println(n + 1) // 43

Concept

Wrap errors on the way up

An error from deep down, like "disk full", needs context as it travels up. fmt.Errorf with the verb %w builds a new error that wraps the old one: the message grows and the original stays reachable.

errors.Is(err, target) walks that chain looking for one specific error value. errors.As looks for an error of a given type and hands it to you. Comparing with == only sees the outermost error.

Go
base := errors.New("disk full")
err := fmt.Errorf("save: %w", base)

fmt.Println(err) // save: disk full
fmt.Println(err == base)          // false
fmt.Println(errors.Is(err, base)) // true

Concept

defer, panic and recover

defer f() schedules a call for when the surrounding function returns, however it returns. It pairs cleanup with setup: open a file, write defer file.Close() on the next line. Deferred calls run last in, first out.

panic is for bugs and impossible states, such as an index out of range. It unwinds the stack, running deferred calls, and crashes the program unless a deferred function calls recover. Expected failures are returned errors.

Go
func save() {
  fmt.Println("open")
  defer fmt.Println("close")
  fmt.Println("write")
}

save()
// open, write, close

9 more exercises in the app

  • 1× order the lines
  • 4× type the answer
  • 3× multiple choice
  • 1× fill the blanks

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy