看下面的代码片段。
package main
import "fmt"
func explode() {
// Cause a panic.
panic("WRONG")
}
func recovery() int {
explode()
defer func() {
fmt.Println("Try to handle panic")
if err := recover(); err != nil {
fmt.Println("FIX")
fmt.Println("ERR", err)
}
}()
fmt.Println("Print value")
return 100
}
func main() {
// Handle errors in defer func with recover.
fmt.Println(recovery())
}
正如你在上面的代码中看到的,我在explode函数中触发了一个panic,并希望在recovery函数中处理它。但是恐慌没有被抓住,我有运行时错误
goroutine 1 [running]:
main.explode()
D:/gocode/src/samples/panic1.go:7 +0x6b
main.recovery(0xc082002250)
D:/gocode/src/samples/panic1.go:18 +0x26
main.main()
D:/gocode/src/samples/panic1.go:27 +0x26
goroutine 2 [runnable]:
runtime.forcegchelper()
c:/go/src/runtime/proc.go:90
runtime.goexit()
c:/go/src/runtime/asm_amd64.s:2232 +0x1
goroutine 3 [runnable]:
runtime.bgsweep()
c:/go/src/runtime/mgc0.go:82
runtime.goexit()
c:/go/src/runtime/asm_amd64.s:2232 +0x1
goroutine 4 [runnable]:
runtime.runfinq()
c:/go/src/runtime/malloc.go:712
runtime.goexit()
c:/go/src/runtime/asm_amd64.s:2232 +0x1
exit status 2
如何捕捉recory函数中的panic?
心有法竹
相关分类