`

go语言goroutine的异常捕获(四)

    博客分类:
  • Go
阅读更多
package main

import "fmt"
import "time"
/*

goroutine中的异常通过defer+recover捕获

*/

func fn1(){

	for i:=0;i<5;i++{
		time.Sleep(time.Millisecond*10)
		fmt.Println("hello")
	}
}


func test(){
	//捕获异常,匿名自执行函数
	defer func(){
		err:= recover()
		if err!=nil{
			fmt.Println("error:", err)  //error: assignment to entry in nil map
		}
	}()

	var mp1 map[int]string
	mp1[0]="abc"
}


func main() {

	go fn1()
	go test()
	time.Sleep(time.Millisecond*100)  //主线程等待协程执行,推荐使用waitGroup
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics