例如:
package mainimport ( "errors" "fmt")func A(s string) (result string, err error) { defer func() { if e := recover(); e != nil { switch x := e.(type) { case error: err = x default: err = fmt.Errorf("%v", x) } } }() B(s) return "returned", nil}func B(s string) { switch s { case "ok": return case "fail": panic(errors.New("failed")) case "fail miserably": panic(42) default: a, b := 1, 0 if a/b != 0 { panic("ouch") } }}func main() { s, err := A("ok") fmt.Printf("%q, %T(%#v)n", s, err, err) s, err = A("fail") fmt.Printf("%q, %T(%#v)n", s, err, err) s, err = A("fail miserably") fmt.Printf("%q, %T(%#v)n", s, err, err) s, err = A("") fmt.Printf("%q, %T(%#v)n", s, err, err)}
输出:
"returned", <nil>(<nil>)"", *errors.errorString(&errors.errorString{s:"failed"})"", *errors.errorString(&errors.errorString{s:"42"})"", runtime.errorString("integer divide by zero")
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)