ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] > [参考](https://ieevee.com/tech/2017/11/23/go-panic.html) ## 接收异常 ### 主线程 ``` defer func() { e := recover() log.Println(e) }() panic("should set user env.") time.Sleep(1 * time.Second) fmt.Printf("i can output") //依然可以输出 //output //2020/01/04 15:43:24 should set user env. ``` ### 在 goruntime 接收异常 实现 try...catch 的效果 在panic的当前goroutine的defer中使用recover来捕捉panic,recover只在defer的函数中有效 ``` defer fmt.Println("defer main") var user = os.Getenv("USER_") go func() { defer func() { err := recover() fmt.Println(err) }() func() { if user == "" { panic("should set user env.") //不会输出异常 } }() }() time.Sleep(1 * time.Second) fmt.Printf("i can output") //依然可以输出 //output //should set user env. //i can outputdefer main ```