1.应用级别,可recover
这些 panic 一般是 逻辑或使用不当导致的运行时错误 ,Go 程序可以用 recover
捕获并继续运行:
类型 | 示例 | 描述 |
---|---|---|
类型不一致 | atomic.Value 存不同类型 v.Store(100); v.Store("abc") |
panic: store of inconsistently typed value |
数组/切片越界 | arr := []int{1,2}; fmt.Println(arr[3]) |
panic: runtime error: index out of range |
空指针引用 | var p *int; fmt.Println(*p) |
panic: runtime error: invalid memory address or nil pointer dereference |
类型断言失败 | var i interface{} = 123; s := i.(string) |
panic: interface conversion: int is not string |
映射访问不存在键 | 不会 panic 直接返回零值;但对 nil map 写入会 panic | |
nil map 写入 | var m map[int]int; m[1]=1 |
panic: assignment to entry in nil map |
channel 关闭写入 | ch := make(chan int); close(ch); ch<-1 |
panic: send on closed channel |
channel 关闭重复 | ch := make(chan int); close(ch); close(ch) |
panic: close of closed channel |
阻塞,不 panic(可选) | ||
runtime 错误 | runtime.Gosched() 不会 panic,但 runtime.Goexit() 会终止当前 goroutine |
|
死锁 | 进程内所有协程都在阻塞 | fatal error: all goroutines are asleep - deadlock! |
2. 系统级别错误,不可recover
类型 | 示例 | 描述 |
---|---|---|
map 并发读写 | m := make(map[int]int); go m[1]=1; go _ = m[2] |
panic: concurrent map read and map write |
栈溢出 | 无限递归函数 | panic: runtime: stack overflow |
内存损坏 | Cgo 直接写越界内存 | runtime panic,无法 recover |
runtime 系统错误 | runtime.Breakpoint() |
调试或系统级 panic,不可 recover |
内存访问非法 | unsafe 包错误操作 | 如访问非法地址、强制类型转换出界 |
signal / SIGSEGV | 非法访问地址 | panic: runtime error: invalid memory address or nil pointer dereference,在系统级别也可能终止进程 |
3. 特殊场景
类型 | 示例 | 描述 |
---|---|---|
nil 函数调用 | var f func(); f() |
panic: call of nil function |
append 到 nil slice | var s []int; s = append(s, 1) |
不 panic,可以正常工作 |
close nil channel | var ch chan int; close(ch) |
panic: close of nil channel |
atomic.Value 读写不一致类型 | v.Store(100); v.Store("abc") |
panic,可 recover |