序
本文次要钻研一下golang的panic与recover
panic与recover
recover在如下三种状况下返回nil
- panic参数为nil
- goroutine没有产生panic
- recover不是在defer func中调用
实例
实例1
var fc func() string
func protect(g func() string) {
defer func() {
fmt.Println("done") // Println executes normally even if there is a panic
if x := recover(); x != nil {
fmt.Printf("run time panic: %v", x)
}
}()
fmt.Println("start")
fmt.Println(g())
}
func main() {
protect(fc)
}
这里fc为nil,因此产生runtime panic,而后被defer的recover捕捉
实例2
func deferRecover() {
defer func() {
fmt.Println("defer1: recover")
if err := recover(); err != nil {
fmt.Println(err)
} else {
fmt.Println("defer1 recover nil")
}
}()
defer func() {
fmt.Println("defer2: recover ")
if err := recover(); err != nil {
fmt.Println(err)
}
}()
panic("manual panic")
defer func() {
fmt.Println("never be executed")
}()
}
这里defer2捕捉了panic,defer1就捕捉不到panic了
实例3
func paincInDefer() {
defer func() {
fmt.Println("defer1 recover")
if err := recover(); err != nil {
// main panic is override by defer2 panic
fmt.Println(err)
} else {
fmt.Println("defer1 recover nil")
}
}()
defer func() {
fmt.Println("defer2 begin to panic")
panic("defer2 panic")
}()
panic("main panic")
}
这里defer2产生了panic,”笼罩”了原始的panic,defer1捕捉的是最初一个panic即defer2产生的panic
实例4
func paincInDeferNotRecover() {
defer func() {
fmt.Println("defer1")
}()
defer func() {
fmt.Println("defer2 begin to panic")
panic("defer2 panic")
}()
panic("main panic")
}
这里defer2产生了panic,defer1没有捕捉,产生的panic顺次显示了main panic及defer2 panic
输入
defer2 begin to panic
defer1
panic: main panic
panic: defer2 panic
goroutine 1 [running]:
main.paincInDeferNotRecover.func2()
实例5
func multiPaincInDefer() {
defer func() {
fmt.Println("defer1")
panic("defer3 panic")
}()
defer func() {
fmt.Println("defer2 begin to panic")
panic("defer2 panic")
}()
panic("main panic")
}
输入
defer2 begin to panic
defer1
panic: main panic
panic: defer2 panic
panic: defer3 panic
goroutine 1 [running]:
main.multiPaincInDefer.func1()
实例6
func panicAfterRecover() {
defer func() {
fmt.Println("defer1")
if err := recover(); err != nil {
panic("defer1 panic after recover")
} else {
fmt.Println("defer1 recover nil")
}
}()
defer func() {
fmt.Println("defer2 begin to panic")
panic("defer2 panic")
}()
panic("main panic")
}
输入
defer2 begin to panic
defer1
panic: main panic
panic: defer2 panic [recovered]
panic: defer1 panic after recover
goroutine 1 [running]:
main.panicAfterRecover.func1()
/defer.go:180 +0x10d
panic(0x10b2020, 0x10eaed0)
/usr/local/go/src/runtime/panic.go:969 +0x1b9
main.panicAfterRecover.func2()
/defer.go:188 +0x95
panic(0x10b2020, 0x10eaee0)
/usr/local/go/src/runtime/panic.go:969 +0x1b9
main.panicAfterRecover()
/defer.go:191 +0x68
main.main()
/defer.go:215 +0x25
exit status 2
小结
- recover必须在defer中调用才能够,多个defer呈现了panic没有recover,则panic信息会列出所有的painc信息
- 如果defer也呈现了panic则若有被recover则recover的是最初一个panic,非defer的panic被”笼罩”
- 如果defer的recover之后呈现了panic,则最初panic会呈现被recover的那个panic信息
doc
- Handling_panics