Go语言 使用defer+recover解决panic导致程序崩溃的问题 (Golang经典编程案例)
package main
import (
"fmt"
"time"
)
func sayHello() {
for i := 0; i < 10; i++ {
time.Sleep(time.Second)
fmt.Println("hello world")
}
}
func test() {
//使用 defer + recover
defer func() {
//捕获test抛出的panic
if err := recover();err!=nil{
fmt.Println("test发生错误",err)
}
}()
//定义一个map
var myMap map[int]string
myMap[0] = "golang" //error
}
func main() {
go sayHello()
go test()
for i := 0; i < 10; i++ {
fmt.Println("main() ok=",i)
time.Sleep(time.Second)
}
}