Home > Backend Development > Golang > Why Does `defer recover()` Fail to Catch Panics, While `defer func() { recover() }()` Succeeds?

Why Does `defer recover()` Fail to Catch Panics, While `defer func() { recover() }()` Succeeds?

Susan Sarandon
Release: 2024-11-30 21:35:17
Original
888 people have browsed it

Why Does `defer recover()` Fail to Catch Panics, While `defer func() { recover() }()` Succeeds?

Why defer recover() Not Catch Panics?

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template