亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何處理外面的恐慌

如何處理外面的恐慌

Go
catspeake 2021-09-13 16:18:08
看下面的代碼片段。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上試一試。


查看完整回答
反對 回復 2021-09-13
  • 2 回答
  • 0 關注
  • 197 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號