Defer Ordering With Panic Recovery
Verify that deferred calls run LIFO and that recover inside a deferred function converts a panic into a normal error return.
Code
package main
import "fmt"
func riskyOperation() (result string, err error) {
defer func() {
if r := recover(); r != nil {
// 命名返回值让 recover 后能正常返回
err = fmt.Errorf("recovered: %v", r)
}
}()
defer fmt.Println("defer 1: runs last (LIFO)")
fmt.Println("before panic")
panic("simulated failure")
}
func main() {
defer fmt.Println("main defer: runs after riskyOperation finishes")
result, err := riskyOperation()
fmt.Println("result:", result, "err:", err)
}Inside the snippet
Everything happens inside the functions riskyOperation and main.
The cleanup call is deferred to function exit — success, early return, and panic all covered.
Caveats
- The environment needs no preparation beyond having the interpreter or compiler.
Using it
The main signature reads func riskyOperation() (result string, err error)
Running the file prints labeled results such as defer 1: runs last (LIFO), before panic, main defer: runs after riskyOperation finishes — each operation’s effect is visible in the output.
Launch the file; main takes over and steps through riskyOperation.
The key statements that remain
func riskyOperation() (result string, err error) {
defer func() {
if r := recover(); r != nil {
// 命名返回值让 recover 后能正常返回
err = fmt.Errorf("recovered: %v", r)
}
}()
defer fmt.Println("defer 1: runs last (LIFO)")
fmt.Println("before panic")
panic("simulated failure")
}
func main() {
defer fmt.Println("main defer: runs after riskyOperation finishes")
result, err := riskyOperation()
fmt.Println("result:", result, "err:", err)
}
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 Ordering With Panic Recovery print when run?
- Execute the whole file; each printed line is prefixed with a label like `defer 1: runs last (LIFO)`, `before panic`, `main defer: runs after riskyOperation finishes`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.