Lesson 2 · Unit 03
Errors as values
A result and an error, checking err, strconv.Atoi, and why ignoring an error is the bug.
What you practise
- A function that returns a value and an
error,if err != nil,strconv.Atoi,errors.Newandfmt.Errorf, why ignoring the error is the bug
Try a question from this lesson
Pick one
This function divides. Its second call asks for something impossible. What do you think happens when the program runs?
func divide(a, b int) int {
return a / b
}
fmt.Println(divide(10, 2))
fmt.Println(divide(1, 0))Correct answer
It prints 5, then crashes
Why
The first call prints 5. The second cannot be done, and Go stops the whole program with "panic: runtime error: integer divide by zero". A crash is a harsh way to report a problem the function could see coming.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Errors are values
In Go, a function that can fail returns two things: its result, and a value of type error that says what went wrong.
When all is well, the error is nil, which means "nothing here". When something is wrong, the function returns an error made with errors.New("..."), and a zero for the result.
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("no zero")
}
return a / b, nil
}Concept
Text into numbers: strconv.Atoi
Text that looks like a number is still text: "42" is a string. strconv.Atoi turns such a string into an int.
It can fail, because not every string is a number, so it returns two values: the number and an error. This is the pattern you will see everywhere in Go: call, then check err before using the result.
n, err := strconv.Atoi("42")
if err != nil {
fmt.Println("not a number")
} else {
fmt.Println(n + 1) // 43
}Concept
Making and passing on errors
errors.New("...") makes an error with a fixed message. fmt.Errorf makes one from a pattern, like Printf, so the message can include the value that caused the trouble.
A function that gets an error it cannot fix usually hands it back to its own caller: return 0, err.
func checkAge(age int) error {
if age < 0 {
return fmt.Errorf("bad age: %d", age)
}
return nil
}
fmt.Println(checkAge(-5)) // bad age: -5
fmt.Println(checkAge(30)) // <nil>9 more exercises in the app
- 3× multiple choice
- 3× type the answer
- 1× fill the blanks
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.