GO / CHAPTER 08
Errors and deferred cleanup
AdvancedMake normal failure explicit and understand when deferred calls run.
By the end of this chapter
- Return and check an error
- Handle an error before using its result
- Trace deferred argument evaluation and execution
The idea
Enter with functions and multiple return values understood. Go commonly returns a result together with an error. A nil error indicates success by convention; a non-nil error should be handled before treating the accompanying result as usable. Expected invalid input should have a clear error path rather than being silently replaced with a plausible answer. The caller decides whether to recover, report, or propagate the problem.
defer schedules a function call for the surrounding function’s return. Its arguments are evaluated when the defer statement executes, while the call itself runs later. Multiple deferred calls run in reverse registration order. This supports cleanup after a resource has been successfully acquired. Be careful about whether the deferred operation captures a value immediately or reads a variable later through a closure.
package main
import "fmt"
func main(){
n:=3
defer fmt.Println(n)
n=8
fmt.Println(n)
}8 3
The normal print reads eight. The deferred call retained its already evaluated argument three and runs as main returns.
Try it yourself
Write a helper returning (int, error) that rejects a negative count with a descriptive error.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING