延迟功能不恢复

defer func not recover

所以,我一直在go中摆弄,发现下面的函数恢复成功了

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")
}

但这不是

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")
}

谁能解释一下为什么?我一直在寻找答案,但没有找到任何我能完全理解的东西。 谢谢。

恢复调用只会在直接从延迟函数调用时停止恐慌。这是来自 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.