英文:
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("X")
}
func rec() {
	rec2()
}
func rec2() {
	fmt.Printf("recovered: %v\n", recover())
}
The output of this is:
recovered: <nil>
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论