本文主要研究一下golang的panic与recover
recover在如下三种情况下返回nil
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捕获
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了
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
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()
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()
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