gorecoverpanicdefer-keyword

Why golang can not recover from a panic in a function called by the defer function


package main

import "fmt"

func myRecover() {
    if r := recover(); r != nil {
        fmt.Println(r)
    }
}

func main() {
    defer func() {
        myRecover()
    }()
    panic("The gas price is skyrocketing!")
}

The code above can not recover from the panic somehow the code below can.

package main

import "fmt"

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println(r)
        }
    }()
    panic("The gas price is skyrocketing!")
}

It is so confusing. I want to know why.


Solution

  • The specification says:

    The return value of recover is nil if any of the following conditions holds:

    • ...
    • recover was not called directly by a deferred function.

    In the first example, recover is not called directly by the deferred function. The recover function always returns nil in this case.

    You can use myRecover by deferring the function directly.

    func main() {
        defer myRecover()
        panic("The gas price is skyrocketing!")
    }