第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何在延遲函數(shù)Go中檢測panic(nil)和正常執(zhí)行?

如何在延遲函數(shù)Go中檢測panic(nil)和正常執(zhí)行?

Go
人到中年有點(diǎn)甜 2021-07-02 10:15:45
go 運(yùn)行時(shí)可以檢測panic(nil)并報(bào)告錯(cuò)誤。但是,我無法在紅色函數(shù)中檢測panic(nil)with recover(),defer因?yàn)樗祷豱il,因此我無法將其與正常執(zhí)行(沒有恐慌)區(qū)分開來,因?yàn)槲視?huì)測試 的返回值recover()是否為零。例如,defer func(){    var err = recover()    if err != nil {       // Real serious situation. Panic from inner code.       // And we may have some critical resources which        // must be cleaned-up at any cases.       // However, this will not be executed for panic(nil)        rollback()       // I am still not sure that how should I treat `panic`…       // Should I just ignore them?    }}()var err = doTransaction()if err == nil {    commit()    // Happy case.} else {    rollback()  // Regular execution. Just a lucky case.}ROLLBACK 只是一個(gè)例子,我想我可以有很多關(guān)鍵情況需要清理。好吧,那些清理代碼也不會(huì)在真正的程序崩潰時(shí)執(zhí)行,但我想盡可能地進(jìn)行辯護(hù)。無論延遲函數(shù)中的參數(shù)如何,如何檢測任何恐慌?
查看完整描述

2 回答

?
明月笑刀無情

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超4個(gè)贊

除非我誤解了您的問題,否則延遲函數(shù)調(diào)用在恐慌時(shí)運(yùn)行,即使傳遞的值為nil以下程序說明了這一點(diǎn):

package mainimport "fmt"func main() {    defer func() {
        fmt.Println("Recover:", recover())
    }()
    panic(nil)}

因此,您可以panic(nil)通過比較recover()to返回的值來輕松檢測是否發(fā)生了nil。

編輯以回答評(píng)論:

是的,這是真的; 延遲調(diào)用通常會(huì)在函數(shù)返回時(shí)運(yùn)行。但是它們也會(huì)在 .a 之后展開調(diào)用堆棧時(shí)運(yùn)行panic()

問題更新后編輯:

您是正確的,沒有辦法區(qū)分這些情況。另一方面,恐慌nil也沒有多大意義——尤其是因?yàn)檫@個(gè)限制。

panic(nil)我能想到的唯一用例是故意避免恢復(fù)并強(qiáng)制程序因堆棧跟蹤而崩潰。不過,還有更優(yōu)雅的方法可以做到這一點(diǎn),runtime例如使用包。


查看完整回答
反對(duì) 回復(fù) 2021-07-05
?
白衣染霜花

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超10個(gè)贊

我可以在退出前設(shè)置一個(gè)標(biāo)志。


AFAIK,panic 是特定于 goroutine 的,并且單個(gè) goroutine 保證在單線程中。因此,不需要在 variable 周圍進(jìn)行同步/鎖定ok。如果我錯(cuò)了,請(qǐng)糾正我。


func clean(ok *bool) {

    if *ok {

        log.Printf("Execution OK. No panic detected.\n")

    } else {

        var reason = recover()

        log.Printf("Some bad thing happen. reason = %v\n", reason)

        panic("Abnormal exit. Program abandoned. Stack-trace here.")

        debug.PrintStack() // Oops. this will not run.

    }

}


func main() {

    var ok bool = false


    defer clean(&ok)

    panic(nil)


    test1() // Here's the main job.


    ok = true

    log.Printf("All work done. Quit gracefully.\n")

}


查看完整回答
反對(duì) 回復(fù) 2021-07-05
  • 2 回答
  • 0 關(guān)注
  • 344 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)