×

go · level 2 · unit 3 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

In Go, an error is a value you check, not a crash.

Lots of things can fail: a number typed as words, a missing file, a lost connection. Go functions that can fail hand back an as their last result. It is nil when everything worked, and describes the problem when it did not.

turns text into a number. n, err := strconv.Atoi(text) catches both results. Check straight away with if err != nil, and only trust n when err is nil.

error is an interface with one method, Error() string, so printing an error shows its message. Handling errors like this keeps your program running and puts every possible failure in plain sight.

package main
import "fmt"
import "strconv"
func main() {
	for _, text := range []string{"42", "forty-two"} {
		n, err := strconv.Atoi(text)
		if err != nil {
			fmt.Println("Problem:", err)
			continue
		}
		fmt.Println("Doubled:", n*2)
	}
}

Go programmers almost always call the box err and check it on the very next line.