【发布时间】:2022-06-27 15:12:45
【问题描述】:
我被提到了这个问题:Program recovered from panic does not exit as expected 它工作得很好,但它依赖于知道恐慌发生在哪里才能放置延迟函数。 我的代码如下。
package main
import "fmt"
func main() {
defer recoverPanic()
f1()
f2()
f3()
}
func f1() {
fmt.Println("f1")
}
func f2() {
defer f3() //<--- don't want to defer f3 here because I might not know f2 will panic, panic could occuer elsewhere
fmt.Println("f2")
panic("f2")
}
func f3() {
fmt.Println("f3")
}
func recoverPanic() {
if r := recover(); r != nil {
fmt.Printf("Cause of panic ==>> %q\n", r)
}
}
在恐慌函数中使用延迟函数调用 f3() 可以工作,输出如下。
f1
f2
f3
Cause of panic ==>> "f2"
如果您的应用程序不知道发生恐慌的位置怎么办,我是否需要在每个可能发生恐慌的函数中添加延迟?
注释掉 defer f3() 会给我以下输出。
f1
f2
Cause of panic ==>> "f2"
f3 从不运行。
我的问题是如何在不延迟函数调用的情况下继续执行程序可能恐慌?
【问题讨论】: