多个panic,recover如何写?

taatcc · · 1574 次点击
建议做统一的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
更多评论
polaris
社区,需要你我一同完善!
1、panic 了,程序在 panic 处中断,recover 只是保证整个程序不会终止; 2、自动 panic ,那是程序有bug,比如 ```go var p *string = nil *p = "studygolang" ``` 会自动 panic
#1
原来是这样,我还以为recover后,能继续往下执行呢。不同于java中的try..catch(){},在捕获后能继续执行<br>
#2