为了账号安全,请及时绑定邮箱和手机立即绑定

Go:从延迟返回

Go:从延迟返回

Go
拉丁的传说 2021-07-10 15:07:13
如果函数发生恐慌(在 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    ...} 我似乎误解了恐慌和推迟的概念。有人可以启发我吗?
查看完整描述

3 回答

?
12345678_0001

TA贡献1802条经验 获得超5个赞

看看这个


package main


import "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())

}


查看完整回答
反对 回复 2021-07-12
  • 3 回答
  • 0 关注
  • 168 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信