一、在协程中的panic(),导致整个程序解体
func TestPanic(t *testing.T) { t.Log("1") go func() { panic("panic") }() time.Sleep(time.Second * 1) //加一下,避免 多个协程(panic协程还没走到,主协程就完结了) t.Log("2")}
输入:
1panic: panicgoroutine 7 [running]:github.com/hisheng/dataStructure/panic.TestPanic.func1() /Users/zhanghaisheng/study/dataStructure/panic/panic_test.go:16 +0x39created by github.com/hisheng/dataStructure/panic.TestPanic /Users/zhanghaisheng/study/dataStructure/panic/panic_test.go:15 +0x85
咱们能够看到,子协程的panic,间接导致了,主协程也蹦了,没法执行上来。
二、go应用recover()来捕获panic(),避免程序解体
func TestRecover(t *testing.T) { t.Log("1") go func() { defer func() { recover() }() panic("panic") }() time.Sleep(time.Second * 1) //加一下,避免 多个协程(panic协程还没走到,主协程就完结了) t.Log("2")}
输入:
12
三、go应用recover()来做一些逻辑解决
recover()有返回值,咱们能够用 recover() != nil来做一些解决
//当panic的时候写入到日志外面func TestRecover2(t *testing.T) { t.Log("1") go func() { defer func() { r := recover() if r != nil { //写入日志 } }() panic("panic") }() time.Sleep(time.Second * 1) //加一下,避免 多个协程(panic协程还没走到,主协程就完结了) t.Log("2")}