Defer Order Panic And Recover
Trace defer's LIFO order around a panic, then recover in a deferred closure so the program keeps running instead of crashing.
Code
package main
import "fmt"
func risky(deep bool) {
// 两条 defer 按后进先出执行:后注册的先跑
defer fmt.Println("first defer in risky")
defer fmt.Println("second defer in risky")
if deep {
panic("bad input")
}
fmt.Println("risky completed normally")
}
func safe(deep bool) {
defer func() {
// recover 只在 defer 中有效:捕获 panic 恢复正常执行流
if r := recover(); r != nil {
fmt.Println("recovered:", r)
}
}()
risky(deep)
}
func main() {
safe(false)
fmt.Println("---")
safe(true)
fmt.Println("main continues after recovery")
}What the code does
The snippet is organized around the functions risky, safe and main.
Deferred at entry, executed at exit: defer keeps cleanup adjacent to acquisition.
Points of care
- No third-party code is loaded at any point while this runs.
Using it
Signature: func risky(deep bool)
The demo output is labeled (first defer in risky, second defer in risky, risky completed normally), so each line traces straight back to the statement that printed it.
There are 1 call inside main — safe — executed top to bottom.
Key statements
if r := recover(); r != nil {
fmt.Println("recovered:", r)
}
func risky(deep bool) {
// 两条 defer 按后进先出执行:后注册的先跑
defer fmt.Println("first defer in risky")
defer fmt.Println("second defer in risky")
if deep {
panic("bad input")
}
fmt.Println("risky completed normally")
}
func main() {
safe(false)
fmt.Println("---")
safe(true)
fmt.Println("main continues after recovery")
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Defer Order Panic And Recover print when run?
- Running the file directly is enough — expect labeled output lines such as `first defer in risky`, `second defer in risky`, `risky completed normally`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.