go · level 2 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
There is a sneaky space. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
import "strconv"
func main() {
age, err := strconv.Atoi("12 ")
if err != nil {
fmt.Println("Not a number")
} else {
fmt.Println("Next year you will be", age+1)
}
}
your turn
Your turn. Buy some cinema tickets.
Type how many tickets you want, as digits such as 3, and run it. Afterwards, try a word such as three to watch the error get handled.
output
press run to see what happens
fix it
Seven is a fine number, but the program complains. Fix it!
output
press run to see what happens
- The text 7 is a perfectly good number, yet the complaint appears. Look at the check on line 6.
nilmeans no error, soerr == nilistruewhen everything worked.- Change == to != on line 6, then run.
nailed it
your program expects the unexpected. :D
- Functions that can fail return an
erroras their last result. nilmeans it worked, so checkif err != nilstraight away.erroris an interface, and printing one shows its message.
new words in your collection
- error value
- Atoi
This lesson isn’t saved. A free account remembers every lesson you finish.