猿问

Go:从延迟返回

如果函数发生恐慌(在 Go 中),我想从它返回一个错误:


func getReport(filename string) (rep report, err error) {

    rep.data = make(map[string]float64)


    defer func() {

        if r := recover(); r != nil {

            fmt.Println("Recovered in f", r)

            err, _ = r.(error)

            return nil, err

        }

    }()

    panic("Report format not recognized.")

    // rest of the getReport function, which can try to out-of-bound-access a slice

    ...

我似乎误解了恐慌和推迟的概念。有人可以启发我吗?


拉丁的传说
浏览 169回答 3
3回答

12345678_0001

看看这个package mainimport "fmt"func iWillPanic() {    panic("ops, panic")}func runner() (s string) {    rtnValue := ""    defer func() {        if r := recover(); r != nil {            // and your logs or something here, log nothing with panic is not a good idea            rtnValue = "don't panic" // modify the return value, and it will return        }    }()    iWillPanic()    return rtnValue}func main() {    fmt.Println("Return Value:", runner())}
随时随地看视频慕课网APP

相关分类

Go
我要回答