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() }()`: Why Does One Recover Panics and the Other Doesn't?

DDD
Release: 2024-11-29 11:27:10
Original
1035 people have browsed it

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")
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template