A common mistake is treating panic as Go's everyday exception mechanism. panic stops ordinary execution, unwinds the current goroutine's call stack, and either terminates that goroutine or reaches recover. section 7.1
func main() {
fmt.Println("a")
panic("foo")
fmt.Println("b")
}
A minimal program prints a, panics, and never reaches the following print statement. section 7.1
Trace panic behavior through these rules:
- A panic moves upward through the current call stack until the goroutine returns or a deferred function recovers it. section 7.1
- recover is useful only inside a defer function; elsewhere it returns nil and has no other effect. section 7.1
- Use panic sparingly for unrecoverable conditions, such as programmer errors or failure to load a mandatory dependency; return ordinary errors otherwise. section 7.1 section 7.8
Recovering at a boundary
A deferred function can call recover while f panics, print the recovered value, and allow main's goroutine to continue. This is a targeted containment mechanism, not a replacement for returning errors. section 7.1
func checkWriteHeaderCode(code int) {
if code < 100 || code > 999 {
panic(fmt.Sprintf("invalid WriteHeader code %v", code))
}
}
An invalid HTTP status code is treated as a programmer error and triggers panic rather than an ordinary returned error. section 7.1







