Go 常见的引发 panic 的情况
- 数组下标越界(运行时错误)
package main
import "fmt"
func main() {
var s []string
fmt.Println(s)
fmt.Println(s[0])
}
运行结果:
[]
panic: runtime error: index out of range
goroutine 1 [running]:
main.main()
- 空指针异常(运行时错误)
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
var p *Person
fmt.Println(p)
fmt.Println(p.Name)
}
运行结果:
<nil>
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x10914c8]
goroutine 1 [running]:
main.main()
- 类型断言失败(接口转换异常)
package main
import "fmt"
func main() {
add(20, 18)
add(1, "hello")
}
func add(a, b interface{}) {
i := a.(int)
j := b.(int)
fmt.Println(i+j)
}
运行结果:
panic: interface conversion: interface {} is string, not int
38
goroutine 1 [running]:
main.add(0x10a0f60, 0x10d6840, 0x10a1660, 0x10d6b90)
- 通道为空,通道已关闭(写数据)
package main
func main() {
var ch chan int
close(ch)
}
运行结果:
panic: close of nil channel
goroutine 1 [running]:
main.main()
package main
func main() {
var ch chan int
ch = make(chan int,0)
close(ch)
ch <- 108
}
运行结果:
panic: send on closed channel
goroutine 1 [running]:
main.main()
- 死锁,所有线程睡眠(致命错误)
这一条是致命错误,不属于异常,但是跟异常一样,会导致程序挂掉。
package main
func main() {
var ch chan int
ch = make(chan int)
ch <- 108
}
运行结果:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
链接:https://www.jianshu.com/p/b9a2c59b2dd3