281_尚硅谷_管道的注意事项和细节(3)

1.channel使用细节和注意事项1.channel使用细节和注意事项

2.goroutine 中使用recover, 解决协程中出现panic, 导致程序崩溃问题。【案例演示】_报错演示2.goroutine 中使用recover, 解决协程中出现panic, 导致程序崩溃问题。【案例演示】_报错演示

package main

import (
	"fmt"
	"time"
)

// 函数1
func sayHello() {
	for i := 0; i < 10; i++ {
		time.Sleep(time.Second)
		fmt.Println("hello", i)
	}
}

// 函数2
func test() {
	// 定义一个map
	var myMap map[int]string
	myMap[0] = "golang" // error
}

// todo 4) goroutine 中使用recover, 解决协程中出现panic, 导致程序崩溃问题。【案例演示】
func main() {
	go sayHello()
	go test()
	for i := 0; i < 10; i++ {
		fmt.Println("main() ok= ", i)
		time.Sleep(time.Second)

	}
}

3.goroutine 中使用recover, 解决协程中出现panic, 导致程序崩溃问题。【案例演示】_在test()中使用defer+recover解决报错3.goroutine 中使用recover, 解决协程中出现panic, 导致程序崩溃问题。【案例演示】_在test()中使用defer+recover解决报错

package main

import (
	"fmt"
	"time"
)

// 函数1
func sayHello() {
	for i := 0; i < 10; i++ {
		time.Sleep(time.Second)
		fmt.Println("hello", i)
	}
}

// 函数2
func test() {
	// ! 这里可以使用defer + recover, 解决协程中出现panic, 导致程序崩溃问题。
	defer func() {
		// 捕获test抛出的panic
		if err := recover(); err != nil {
			// ! 做出异常报错后要有的处理,比如邮箱通知,或者记录log日志
			fmt.Println("test() 发生错误, 邮箱通知, 或者记录log日志, 报错信息= ", err)
		}
	}()

	// 定义一个map
	var myMap map[int]string
	myMap[0] = "golang" // error
}

// todo 4) goroutine 中使用recover, 解决协程中出现panic, 导致程序崩溃问题。【案例演示】
func main() {
	go sayHello()
	go test()
	for i := 0; i < 10; i++ {
		fmt.Println("main() ok= ", i)
		time.Sleep(time.Second)

	}
}

4.goroutine 中使用recover, 解决协程中出现panic, 导致程序崩溃问题。【案例演示】_运行结果4.goroutine 中使用recover, 解决协程中出现panic, 导致程序崩溃问题。【案例演示】_运行结果

 

posted on 2026-03-07 21:48  与太阳肩并肩  阅读(0)  评论(0)    收藏  举报

导航