一、在协程中的panic(),导致整个程序崩溃
func TestPanic(t *testing.T) {
t.Log("1")
go func() {
panic("panic")
}()
time.Sleep(time.Second * 1) //加一下,防止 多个协程(panic协程还没走到,主协程就结束了)
t.Log("2")
}
输出:
1
panic: panic
goroutine 7 [running]:
github.com/hisheng/dataStructure/panic.TestPanic.func1()
/Users/zhanghaisheng/study/dataStructure/panic/panic_test.go:16 +0x39
created 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")
}
输出:
1
2
三、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")
}