调用函数会中断 recover() 吗?

huangapple go评论146阅读模式
英文:

Does calling a function break recover()?

问题

我正在使用一个从恐慌中恢复的库,它使用的代码简化为以下内容:

func main() {
    defer rec()
    panic("X")
}

func rec() {
    rec2()
}

func rec2() {
    fmt.Printf("recovered: %v\n", recover())
}

这段代码的输出是:

recovered: <nil>
panic: X
...更多的恐慌输出...

值得注意的是,recover()返回的是nil而不是错误。这是预期的行为吗?

英文:

I was using a library which recover()s from panics, and it was using code that simplifies to the following:

func main() {
	defer rec()
	panic(&quot;X&quot;)
}

func rec() {
	rec2()
}

func rec2() {
	fmt.Printf(&quot;recovered: %v\n&quot;, recover())
}

The output of this is:

recovered: &lt;nil&gt;
panic: X
... more panic output ...

Notably, recover() returns nil instead of the error. Is this intended behavior?

答案1

得分: 3

recover 必须由延迟函数直接调用。

根据语言规范

如果满足以下任一条件,则 recover 的返回值为 nil

  • panic 的参数为 nil
  • 协程没有发生恐慌;
  • recover 不是由延迟函数直接调用的。
英文:

recover must be called directly by a deferred function.

from the language spec:

> The return value of recover is nil if any of the following conditions
> holds:
>
> - panic's argument was nil;
> - the goroutine is not panicking;
> - recover was not called directly by a deferred function.

huangapple
  • 本文由 发表于 2016年4月20日 04:07:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/36728419.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定