如果函数发生恐慌(在 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())
}
- 3 回答
- 0 关注
- 168 浏览
添加回答
举报
0/150
提交
取消