一、 错误指程序中出现不正常的状况,从而致使程序没法正常执行。
•大多语言中使用try... catch... finally语句执行。
假设咱们正在尝试打开一个文件,文件系统中不存在这个文件。这是一个异常状况,它表示为一个错误。
二、 Go语言中没有try...catchgit
go中error的源码github
package errors // New returns an error that formats as the given text. // Each call to New returns a distinct error value even if the text is identical. func New(text string) error { return &errorString{text} } // errorString is a trivial implementation of error. type errorString struct { s string } func (e *errorString) Error() string { return e.s }
package main import ( "math" "fmt" "os" "github.com/pkg/errors" ) func main() { // 异常状况1 res := math.Sqrt(-100) fmt.Println(res) res , err := Sqrt(-100) if err != nil { fmt.Println(err) } else { fmt.Println(res) } //异常状况2 //res = 100 / 0 //fmt.Println(res) res , err = Divide(100 , 0) if err != nil { fmt.Println(err.Error()) } else { fmt.Println(res) } //异常状况3 f, err := os.Open("/abc.txt") if err != nil { fmt.Println(err) } else { fmt.Println(f.Name() , "该文件成功被打开!") } } //定义平方根运算函数 func Sqrt(f float64)(float64 , error) { if f<0 { return 0 , errors.New("负数不能够获取平方根") } else { return math.Sqrt(f) , nil } } //定义除法运算函数 func Divide(dividee float64 , divider float64)(float64 , error) { if divider == 0 { return 0 , errors.New("出错:除数不能够为0!") } else { return dividee / divider , nil } }
go中error的建立方式ide
//error建立方式一 func Sqrt(f float64)(float64 , error) { if f<0 { return 0 , errors.New("负数不能够获取平方根") } else { return math.Sqrt(f) , nil } } //error建立方式二;设计一个函数:验证年龄。若是是负数,则返回error func checkAge(age int) (string, error) { if age < 0 { err := fmt.Errorf("您的年龄输入是:%d , 该数值为负数,有错误!", age) return "", err } else { return fmt.Sprintf("您的年龄输入是:%d ", age), nil } }
• 一、定义一个结构体,表示自定义错误的类型
• 二、让自定义错误类型实现error接口的方法:Error() string
• 三、定义一个返回error的函数。根据程序实际功能而定。函数
package main import ( "time" "fmt" ) //一、定义结构体,表示自定义错误的类型 type MyError struct { When time.Time What string } //二、实现Error()方法 func (e MyError) Error() string { return fmt.Sprintf("%v : %v", e.When, e.What) } //三、定义函数,返回error对象。该函数求矩形面积 func getArea(width, length float64) (float64, error) { errorInfo := "" if width < 0 && length < 0 { errorInfo = fmt.Sprintf("长度:%v, 宽度:%v , 均为负数", length, width) } else if length < 0 { errorInfo = fmt.Sprintf("长度:%v, 出现负数 ", length) } else if width < 0 { errorInfo = fmt.Sprintf("宽度:%v , 出现负数", width) } if errorInfo != "" { return 0, MyError{time.Now(), errorInfo} } else { return width * length, nil } } func main() { res , err := getArea(-4, -5) if err != nil { fmt.Printf(err.Error()) } else { fmt.Println("面积为:" , res) } }