The Question:
Why does a call to defer func() { recover() }() successfully recover a panicking goroutine, but a call to defer recover() not?
The Answer:
As per the documentation of recover(), "If recover is called outside the deferred function, it will not stop a panicking sequence."
In the case of defer recover(), recover() itself is the deferred function. Therefore, it does not call itself, leading to a continued panicking sequence.
If recover() were to call itself as the deferred function, it would stop the panicking sequence. However, this would be illogical.
An Interesting Variant:
The following code also avoids a panic:
package main func main() { var recover = func() { recover() } defer recover() panic("panic") }
Here, we create a recover variable with a function value that calls the built-in recover() function. By deferring the call to this variable's value, we invoke the built-in recover(), which then stops the panicing sequence.
The above is the detailed content of Why Does `defer recover()` Fail to Catch Panics, While `defer func() { recover() }()` Succeeds?. For more information, please follow other related articles on the PHP Chinese website!