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.

GoResilience

Code

gosnippet
22 lines
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

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`.