协程保护:panic捕获

发布时间:2018-04-06 21:42:08
Go 

程序示例

package main

import (
	"fmt"
	"time"
)

func main() {
	for {
		go subFunc()
		time.Sleep(time.Second)
	}
}

func subFunc() {
	//保护程序不因某个协程发生panic而崩溃
	defer func() {
		//panic捕获
		if err := recover(); err != nil {
			fmt.Println("recover")
		}
	}()

	fmt.Println("hello")
	//触发panic
	panic("something wrong happened")
}

参考