Recover()'s Behavior in Nested Deferred Functions
In Go, panic() and recover() are used to handle runtime errors. However, recoverable errors must be handled by deferred functions.
Simple Case:
In a simple deferred function scenario, recover() functions as expected:
package main import "fmt" func printRecover() { r := recover() fmt.Println("Recovered:", r) } func main() { defer printRecover() panic("OMG!") }
Nested Deferred Case:
When printRecover() is wrapped in a nested deferred function:
func main() { defer func() { printRecover() }() panic("OMG!") }
the behavior changes. recover() in printRecover() returns nil. This is because:
According to the Go spec:
The return value of recover() is nil if recover() was not called directly by a deferred function.
In the nested case, printRecover() is called by the nested deferred function, not directly by the initial one.
Conclusion:
For recover() to work in nested deferred functions, it must be called directly by the deferred function that handles the panic. When this condition is not met, recover() will return nil.
The above is the detailed content of Why Does `recover()` Return `nil` in Nested Deferred Functions in Go?. For more information, please follow other related articles on the PHP Chinese website!