Home >Backend Development >Golang >Why Doesn't `defer recover()` Catch Panics in Go?

Why Doesn't `defer recover()` Catch Panics in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-12-05 02:08:09886browse

Why Doesn't `defer recover()` Catch Panics in Go?

When Does defer recover() Fail to Catch Panics?

In Go, defer functions are executed in reverse order of their declaration when a function returns normally or panics. While defer func() { recover() }() effectively recovers from panics, the same is not true for defer recover().

This behavior stems from the documentation of recover(), which states that "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, and hence does not call itself.

Example:

Consider the following code:

package main

func main() {
    defer recover()
    panic("panic")
}

This code will indeed panic with the message "panic: panic," indicating that defer recover() did not prevent the panic.

Working Example:

In contrast, the following code successfully recovers from the panic:

package main

func main() {
    defer func() { recover() }()
    panic("panic")
}

In this case, the anonymous function is called when the main function returns or panics. Within this anonymous function, recover() is called, successfully capturing and preventing the panic.

Exceptional Example:

Interestingly, the following code also avoids the panic:

package main

func main() {
    var recover = func() { recover() }
    defer recover()
    panic("panic")
}

Here, the recover function variable holds a reference to the anonymous function that calls the built-in recover(). Specifying this variable as the deferred function effectively calls the built-in recover(), halting the panic.

The above is the detailed content of Why Doesn't `defer recover()` Catch Panics in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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