看下面的代碼片段。package mainimport "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 +0x6bmain.recovery(0xc082002250) D:/gocode/src/samples/panic1.go:18 +0x26main.main() D:/gocode/src/samples/panic1.go:27 +0x26goroutine 2 [runnable]:runtime.forcegchelper() c:/go/src/runtime/proc.go:90runtime.goexit() c:/go/src/runtime/asm_amd64.s:2232 +0x1goroutine 3 [runnable]:runtime.bgsweep() c:/go/src/runtime/mgc0.go:82runtime.goexit() c:/go/src/runtime/asm_amd64.s:2232 +0x1goroutine 4 [runnable]:runtime.runfinq() c:/go/src/runtime/malloc.go:712runtime.goexit() c:/go/src/runtime/asm_amd64.s:2232 +0x1exit status 2如何捕捉recory函數中的panic?
2 回答

心有法竹
TA貢獻1866條經驗 獲得超5個贊
如果您explode()先調用,則將處理panic并嘗試恢復的函數尚未注冊(并且永遠不會注冊,因為您調用了panicinside explode()),因此不會調用它,顯然它無法完成其工作。
您必須先調用defer,然后調用explode()函數:
defer func() {
// recover() here, Your code omitted
}()
explode()
在Go Playground上試一試。
- 2 回答
- 0 關注
- 197 瀏覽
添加回答
舉報
0/150
提交
取消