package main import ( "fmt" "math" ) //自定义结构体错误,实现error接口 type InvaildradiusError struct { radius float64 Minradius float64 Maxreaius float64 } //封装工厂方法 func NewInvaildradiusError(radius float64)*InvaildradiusError { ire := new(InvaildradiusError) ire.radius= radius ire.Minradius= 5 ire.Maxreaius=50 return ire } func (ire *InvaildradiusError) Error() string { //fmt.Sprintf()不打印结果,将结果返回 info := fmt.Sprintf("%.2F不是合法半径,合法半径的取值范围是[%.2F,%.2F]", ire.radius, ire.Minradius, ire.Maxreaius) return info } func GetToyBallvolume3(radius float64) (volume float64, err error) { if radius < 0 { //redius 为负数,直接返回恐慌 //panic(InvaildradiusError{redius, 5, 50}) panic(NewInvaildradiusError(radius)) } //给小球半径路径设定取值范围,[5,50],不在此范围则返回错误 fmt.Println("来到此处") if radius < 5 || radius > 50 { //err = &InvaildradiusError{radius, 5, 50} err = NewInvaildradiusError(radius) return } return (4 / 3.0 * math.Pi * math.Pow(radius, 3)), nil } func main() { defer func() { if err := recover(); err != nil{ fmt.Println(err) } }() volume, err := GetToyBallvolume3(-4) if err != nil { fmt.Println("获取体积失败,err=", err) return } fmt.Println("小球的体积是:", volume) }