```go
package main
import (
"fmt"
)
func main() {
test()
}
func test() {
defer func() {
if err := recover(); err != nil {
fmt.Println("e1:",err)
}
}()
panic("no1")
defer func() {
if err := recover(); err != nil {
fmt.Println("e2:",err)
}
}()
panic("no2")
}
```
本以为会输出no1、no2,但只输出no1<br>
以为panic("no1")会被第1个recover捕获,然后继续执行panic("no2")<br>
为什么recover会导致退出当前函数?<br>
以上panic是手动panic的,go能否根据一段代码进行判断,然后自动panic?<br>
建议做统一的recover封装,类似:
```golang
package main
import (
"fmt"
"github.com/nothollyhigh/kiss/util"
)
func test() {
defer util.HandlePanic()
fmt.Println(111)
panic("err 1")
fmt.Println(222)
}
func main() {
test()
}
```
输出:
```text
PS C:\Users\Administrator\Desktop> go run .\test.go
111
2019-09-01 17:46:20.315 [Error] [panic.go:43]
---------------------------------------
runtime error: err 1
traceback:
stack: 1 true [file: C:/Users/Administrator/Desktop/test.go] [func: main.test] [line: 12]
stack: 2 true [file: C:/Users/Administrator/Desktop/test.go] [func: main.main] [line: 17]
stack: 3 true [file: d:/dev/go/src/runtime/proc.go] [func: runtime.main] [line: 200]
stack: 4 true [file: d:/dev/go/src/runtime/asm_amd64.s] [func: runtime.goexit] [line: 1337]
---------------------------------------
```
#4
更多评论
1、panic 了,程序在 panic 处中断,recover 只是保证整个程序不会终止;
2、自动 panic ,那是程序有bug,比如
```go
var p *string = nil
*p = "studygolang"
```
会自动 panic
#1