Home >Backend Development >Golang >Defer `recover()` vs. `defer func() { recover() }()`: Why Does One Recover Panics and the Other Doesn't?
defer recover() vs. defer func() { recover() }()
Q: Why does a call to defer func() { recover() }() successfully recover a panicking goroutine, while a call to defer recover() does not?
A: As stated in the official documentation for recover():
"If recover is called outside the deferred function it will not stop a panicking sequence."
In the case of defer recover(), recover() is the deferred function itself. When executed, recover() does not call itself. Therefore, it fails to stop the panicking sequence.
If recover() could call itself, it would stop the panic. However, this scenario is not feasible.
Additional Considerations:
The following code also avoids panicking:
package main func main() { var recover = func() { recover() } defer recover() panic("panic") }
In this case, a variable named recover of function type is created to store an anonymous function that calls the built-in recover() function. The deferred function is then set to call the value of the recover variable. This successfully stops the panicking sequence by indirectly invoking the recover() function.
The above is the detailed content of Defer `recover()` vs. `defer func() { recover() }()`: Why Does One Recover Panics and the Other Doesn't?. For more information, please follow other related articles on the PHP Chinese website!