Home > Backend Development > Golang > Why Does `recover()` Return `nil` in Nested Deferred Functions in Go?

Why Does `recover()` Return `nil` in Nested Deferred Functions in Go?

Patricia Arquette
Release: 2024-11-24 06:56:09
Original
995 people have browsed it

Why Does `recover()` Return `nil` in Nested Deferred Functions in Go?

Recover()'s Behavior in Nested Deferred Functions

In Go, panic() and recover() are used to handle runtime errors. However, recoverable errors must be handled by deferred functions.

Simple Case:

In a simple deferred function scenario, recover() functions as expected:

package main

import "fmt"

func printRecover() {
    r := recover()
    fmt.Println("Recovered:", r)
}

func main() {
    defer printRecover()
    panic("OMG!")
}
Copy after login

Nested Deferred Case:

When printRecover() is wrapped in a nested deferred function:

func main() {
    defer func() {
        printRecover()
    }()
    panic("OMG!")
}
Copy after login

the behavior changes. recover() in printRecover() returns nil. This is because:

According to the Go spec:

The return value of recover() is nil if recover() was not called directly by a deferred function.

In the nested case, printRecover() is called by the nested deferred function, not directly by the initial one.

Conclusion:

For recover() to work in nested deferred functions, it must be called directly by the deferred function that handles the panic. When this condition is not met, recover() will return nil.

The above is the detailed content of Why Does `recover()` Return `nil` in Nested Deferred Functions 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