gorecoverpanicdefer-keyword

defer func not recover


So, I've been fiddling around with go, and I found that function below recover successfully

package main

import (
    "fmt"
)

func a() {  
    defer func(){
        if r := recover(); r != nil {
            fmt.Println("Recovered", r)
        }
    }()
    n := []int{5, 7, 4}
    fmt.Println(n[3])
    fmt.Println("normally returned from a")
}

func main() {  
    a()
    fmt.Println("normally returned from main")
}

But this is not

package main

import (
    "fmt"
)

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

func a() {  
    defer func(){
        r()
    }()
    n := []int{5, 7, 4}
    fmt.Println(n[3])
    fmt.Println("normally returned from a")
}

func main() {  
    a()
    fmt.Println("normally returned from main")
}

Can anybody explain why? I've been looking for answer but did not found anything that i can fully understand. Thank you.


Solution

  • A call to recover will only stop a panic when called directly from the deferred function. Here's the relevant text from the recover documentation:

    Executing a call to recover inside a deferred function (but not any function called by it) stops the panicking sequence by restoring normal execution and retrieves the error value passed to the call of panic.