Lesson 2 · Unit 02
Errors
Return them, check them, wrap them, and save panic for bugs.
What you practise
erroris a value you return,if err != nil, wrapping with%w,errors.Isanderrors.As,defer,panicandrecoverand 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?
n, err := strconv.Atoi("12a")
fmt.Println(n, err != nil)Correct answer
0 true
Why
Nothing is thrown. Atoi returns the zero value and a non-nil error, and the program carries on to the next line. Whether to stop, retry or use a default is the caller's decision, made right where the call happens.
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.
n, err := strconv.Atoi("42")
if err != nil {
fmt.Println("bad number:", err)
return
}
fmt.Println(n + 1) // 43Concept
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.
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)) // trueConcept
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.
func save() {
fmt.Println("open")
defer fmt.Println("close")
fmt.Println("write")
}
save()
// open, write, close9 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.