code:
func tryRecover() {
defer func() {
r := recover()
if err, ok := r.(error); ok {
fmt.Println("Error occurred: ", err)
} else {
// 无法转换error时,只能panic处理
panic(fmt.Sprintf(“I don’t know what to do: %v”, r))
}
}()
}
result:
ok
panic: I don’t know what to do:
goroutine 1 [running]:
main.tryRecover.func1()
D:/Go/depthgo/errhanding/recover/recover.go:14 +0xf9
main.tryRecover()
D:/Go/depthgo/errhanding/recover/recover.go:25 +0x85
main.main()
D:/Go/depthgo/errhanding/recover/recover.go:28 +0x17
老师,执行的代码里面没有报错,还是会进入到 defer func () { recover()}函数里面,触发panic了,这个要怎么处理?