问题描述
为什么调用defer func() { recover() }()
成功恢复了恐慌的goroutine,但是调用defer recover()
却没有成功?
Why does a call to defer func() { recover() }()
successfully recover a panicking goroutine, but a call to defer recover()
not?
作为一个简单的示例,此代码不会惊慌
As an minimalistic example, this code doesn't panic
package main
func main() {
defer func() { recover() }()
panic("panic")
}
但是,将匿名函数替换为直接恢复紧急情况
However, replacing the anonymous function with recover directly panics
package main
func main() {
defer recover()
panic("panic")
}
推荐答案
处理恐慌部分提到
recover
功能允许程序管理紧急恐慌例程的行为.
The recover
function allows a program to manage behavior of a panicking goroutine.
假设函数G
推迟了调用recover
的函数D
,并且panic
在执行G
的同一goroutine上的函数中出现.
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.
当递延函数的运行达到D
时,D
调用recover
的返回值将是传递给panic调用的值.
如果D正常返回而没有开始新的恐慌,恐慌序列将停止.
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.
If D returns normally, without starting a new panic, the panicking sequence stops.
这说明recover
应该在延迟函数中调用,而不是直接调用.
出现紧急情况时,递延函数"不能是内置的recover()
,而是在 defer语句中指定的函数. .
That illustrates that recover
is meant to be called in a deferred function, not directly.
When it panic, the "deferred function" cannot be the built-in recover()
one, but one specified in a defer statement.
DeferStmt = "defer" Expression .
除了特定的内置函数,函数和方法调用以及接收操作可以出现在语句上下文中.
With the exception of specific built-in functions, function and method calls and receive operations can appear in statement context.
这篇关于为什么`defer recovery()`不会引起恐慌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!