如何捕获协程里面出现的错误

//使用defer来预防协程发生错误
package main

import (
	"fmt"
	"time"
)
func sayHello(){
	//备注使用defer 来进行预判  recover()来进行捕获错误发生
	defer  func(){
		if err:=recover(); err!=nil {
			fmt.Println("test() is error");
		}
	}()
	for i:=0;i<10;i++ {
		fmt.Println(i);
	}
}
func main (){
	go sayHello();
	time.Sleep(time.Second * 5);
}

  1.使用defer 来执行某个函数,并且使用recover()来捕获错误如果有错误执行

原文地址:https://www.cnblogs.com/zh718594493/p/14170465.html