doudieheng5322 2014-09-26 20:51
浏览 37
已采纳

恐慌并从包裹中恢复

I'm trying to figure out how panic() and recover() works..

log package

package log

import (
    "fmt"
)

func Recover() {
    fmt.Println("Recovering!")
    if err := recover(); err != nil {
        fmt.Println("Error message recovered!")
    }
}

main package

package main

import (
    "fmt"
    log "www/pkg/log"
)

func main() {
    defer func() {
        log.Recover()
    }()

    panic("Fake error!")
}

output

Recovering!
panic: Fake error!

Why is Error message recovered! never printed?

  • 写回答

2条回答 默认 最新

  • douna6802 2014-09-26 21:00
    关注

    The application must call recover directly from the deferred function to handle the panic.

    The specification talks about the deferred function calling recover:

    Suppose a function G defers a function D that calls recover and a panic occurs in a function on the same goroutine in which G is executing. When the running of deferred functions reaches D, the return value of D's call to recover will be the value passed to the call of panic.

    It's subtle, but it does not allow for an indirect call to recover. Also, the passage on the return value from recover mentions a direct call from the deferred function:

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

    • recover was not called directly by a deferred function.

    I was caught by this issue recently. Because the specification is very concise, it sometimes takes careful reading to pick up some points.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿