不会飞的章鱼

熟能生巧,勤能补拙;念念不忘,必有回响。

让Go“恐慌”的十种方法

本内容来源于书籍《Go语言编程之旅》

本文内容将运行让Go程序遇到“恐慌”的代码例子

数组/切片索引越界

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import "fmt"

func main() {
names := []string{
"1",
"2",
"3",
}
name := names[len(names)] //应该改为 names[len(names) - 1]
fmt.Printf("name: %s",name) //panic: runtime error: index out of range [3] with length 3
}

空指针调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

type User struct {
Name string
}

func (u *User)GetName() string {
return u.Name
}

func main() {
s := &User{Name: "Neo"}
s = nil
s.GetName() //panic: runtime error: invalid memory address or nil pointer dereference
}

过早关闭HTTP响应体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import (
"log"
"net/http"
)

func main() {
resp,err := http.Get("https://xxx")
defer resp.Body.Close() //panic: runtime error: invalid memory address or nil pointer dereference
if err != nil {
log.Fatalf("http.Get err: %v",err)
}
}

除以零

1
2
3
4
5
6
7
8
9
package main

func divide(a,b int) int {
return a / b
}

func main() {
divide(1,0) //panic: runtime error: integer divide by zero
}

向已经关闭的通道发送消息

1
2
3
4
5
6
7
8
package main

func main() {
ch := make(chan string,1)
ch <- "neo"
close(ch)
ch <- "come on" //panic: send on closed channel
}

重复关闭通道

1
2
3
4
5
6
7
8
package main

func main() {
ch := make(chan string,1)
ch <- "neo"
close(ch)
close(ch) //panic: close of closed channel
}

关闭未初始化的通道

1
2
3
4
5
6
package main

func main() {
var ch chan string
close(ch) //panic: close of nil channel
}

未初始化map

1
2
3
4
5
6
package main

func main() {
var m map[string]string
m["neo"] = "come on" //panic: assignment to entry in nil map
}

跨协程的“恐慌”处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
"log"
"time"
)

func main() {
go func() {
defer func() {
if err := recover();err != nil {
log.Fatalf("revover err: %v",err)
}
}()
handle()
}()
time.Sleep(time.Second)
}

func handle() {
go divide(1,0)
}

func divide(a,b int) int {
return a / b //panic: runtime error: integer divide by zero
}

sync计数为负值

1
2
3
4
5
6
7
8
9
package main

import "sync"

func main() {
wg := sync.WaitGroup{}
wg.Add(-1) //panic: sync: negative WaitGroup counter
wg.Wait()
}

代码地址

------ 本文结束------
如果本篇文章对你有帮助,可以给作者加个鸡腿~(*^__^*),感谢鼓励与支持!