【Go】异常处理之自定义异常

2021-09-16 10:43:32 浏览数 (1)

代码语言:javascript复制
package main

import (
	"fmt"
	"math"
)

type IRE struct {
	Radius float64
	MinRadius float64
	MaxRadius float64
}

func newIRE(radius float64) *IRE {
	ire := new(IRE)
	ire.MinRadius = 5
	ire.MaxRadius =50
	ire.Radius = radius
	return ire
}

func (ire *IRE) Error () string {
	info := fmt.Sprintf("%f是非法半径,合法半径的范围是[%f,%f]n", ire.Radius, ire.MinRadius, ire.MaxRadius)
	return info
}
func GetToyBallVolumn3(radius float64) (volumn float64,err error) {
	//什么时候恐慌
	if radius<0{
		//panic(&IRE{0.5,5,50})
		panic(newIRE(radius))
		return
	}
	if radius<5||radius>50{
		err = newIRE(radius)
		//err = &IRE{0.5,5,50}
	}
	return (4.0/3.0) * math.Pi * math.Pow(radius,3),err


}

func main() {
	defer func() {
		//从恐慌中复活,找到导致恐慌的原因
		if err:=recover();err!=nil{
			fmt.Println(err)
		}
	}()
	volumn3,err:= GetToyBallVolumn3(-2)
	if err!=nil{
		fmt.Println(err)
		return
	}
	fmt.Println(volumn3)
}

0 人点赞