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

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

Linda Hamilton
Release: 2024-12-05 02:08:09
Original
877 people have browsed it

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

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

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

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!

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