例如:
package main
import (
"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")