Deferring recover() vs. defer recover()
In Go, a panic can be caught and handled using the recover() function. However, it's important to note that the placement of defer relative to the recover() call has significant implications.
Scenario A: defer func() { recover() }()
In this scenario, the defer statement schedules an anonymous function to be executed at the end of the current function. When this function is executed, it invokes the recover() function. This is an effective way to catch and handle panics because the recover() function will be executed even if a panic occurs before the enclosing function resumes execution.
Scenario B: defer recover()
In this scenario, the recover() function itself is scheduled as a deferred function. However, this doesn't work as intended because recover() doesn't call itself. Therefore, any panics that occur before the enclosing function resumes execution will not be caught by this deferred call.
This behavior is documented in the Go documentation: "If recover is called outside the deferred function it will not stop a panicking sequence."
An Interesting Example: defer (func() { recover() })()
To illustrate this further, consider the following code:
var recover = func() { recover() } defer recover() panic("panic")
Surprisingly, this code also doesn't panic. In this case, we create a recover variable of function type and initialize it to an anonymous function that calls the built-in recover(). We then specify the value of the recover variable as the deferred function. This allows us to catch and handle the panic because the deferred function effectively calls recover(), stopping the panicking sequence.
The above is the detailed content of Go Panic Recovery: Deferring `recover()` – What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!