go · level 2 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Your own functions can hand back errors too.
Your functions can fail as well. Say the cinema sells at most 10 tickets per order. A buy function can return two results, (int, error): the price when all is well, or an error saying what went wrong.
makes an error value with a fixed message. works like Sprintf and builds an error from placeholders: fmt.Errorf("%v is too many", tickets).
Check the bad cases first and , handing back the zero value with the error: return 0, err. At the end, once every check has passed, return the real answer and nil.
package main
import "errors"
import "fmt"
func buy(tickets int) (int, error) {
if tickets < 1 {
return 0, errors.New("buy at least one ticket")
}
if tickets > 10 {
return 0, fmt.Errorf("%v is too many, the limit is 10", tickets)
}
return tickets * 4, nil
}
func main() {
for _, n := range []int{2, 0, 12} {
price, err := buy(n)
fmt.Println(price, err)
}
} Error messages start with a small letter and end without a full stop, because they often get joined onto other text.
guess first
A long name for the class register. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "errors"
import "fmt"
func checkName(name string) error {
if name == "" {
return errors.New("name is empty")
}
if len(name) > 8 {
return fmt.Errorf("%v is longer than 8 letters", name)
}
return nil
}
func main() {
fmt.Println(checkName("Bartholomew"))
}
your turn
Your turn. Guard the big rollercoaster.
Choose the smallest height in cm allowed on the ride. Fill in what rideCheck returns when all is well. Then pick a height that lets you on.
output
press run to see what happens
fix it
Sharing sweets with nobody. Can you fix it?
output
press run to see what happens
- Read the error on line 6. Which type does Go expect first in that
return? - The function promises
(int, error): the number first, then the error. - Swap them so line 6 says return 0, errors.New("nobody to share with"), then run.
nailed it
your functions can say what went wrong. :D
errors.Newmakes an error with a fixed message.fmt.Errorfbuilds an error message with placeholders.- Check for problems first, and return early with the zero value.
new words in your collection
- errors.New
- Errorf
- return early
This lesson isn’t saved. A free account remembers every lesson you finish.