序
本文主要研究一下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信息
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。