panic / recover
最后更新于:2022-04-02 02:42:00
[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
```
';