dpwfh874876 2018-03-18 04:30
浏览 38
已采纳

为什么restore()在嵌套的延迟函数中不起作用?

I am testing panic/recover in Golang. This simple program works as expected:

package main

import "fmt"

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

func main() {
    defer printRecover()

    panic("OMG!")
}

Output:

Recovered: OMG!

However, if I wrap the function printRecover() in a bigger deferred function:

package main

import "fmt"

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

func main() {
    defer func() {
        printRecover()
    }()

    panic("OMG!")
}

It does not recover and let the panic go through:

Recovered: <nil>
panic: OMG!

goroutine 1 [running]:
main.main()
    /tmp/sandbox898315096/main.go:15 +0x60

Can someone explain the difference?

  • 写回答

1条回答 默认 最新

  • douao1854 2018-03-18 04:58
    关注

    It is because recover will be nil if not directly called by deferred function

    Here is excerpt from golang spec

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

    1. panic's argument was nil;
    2. the goroutine is not panicking;
    3. recover was not called directly by a deferred function.

    For more info check the full spec here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!