⼀、错误处理
(⼀)、错误是什么?
1、错误指程序中出现不正常的情况,从⽽导致程序⽆法正常执⾏。
⼤多语⾔中使⽤try...catch...finally语句执⾏。
假设我们正在尝试打开⼀个⽂件,⽂件系统中不存在这个⽂件。这是⼀个
异常情况,它表示为⼀个错误。
不要忽略错误。永远不要忽略⼀个错误。忽视错误会招致麻烦。让我重新
编写⼀个示例,该示例列出了与模式匹配的所有⽂件的名称,⽽忽略了错误
处理代码。
2、Go语⾔中没有try...catch
Go 语⾔通过内置的错误类型提供了⾮常简单的错误处理机制。
错误值可以存储在变量中,通过函数中返回。
如果⼀个函数或⽅法返回⼀个错误,按照惯例,它必须是函数返回的最后
⼀个值。
处理错误的惯⽤⽅式是将返回的错误与nil进⾏⽐较。
nil值表示没有发⽣错误,⽽⾮nil值表示出现错误。
如果不是nil,需打印输出错误。
3、error错误类型的本质
error本质上是⼀个接⼝类型,其中包含⼀个Error()⽅法。
type error interface {
Error() string
}
任何实现这个接⼝的类型都可以作为⼀个错误使⽤。这个⽅法提供了对错误
Go错误处理——error
的描述。
(⼆)、创建error对象的⼏种⽅式
1、errors包下的New()函数返回error对象
errors.New()创建新的错误。
代码分析
// Package errors implements functions to manipulate
errors.
package errors
// New returns an error that formats as the given text.
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
}
2、fmt包下的Errorf()函数返回error对象
fmt包下的Errorf()函数本质上还是调⽤errors.New()
// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
func Errorf(format string, a ...interface{}) error {
return errors.New(Sprintf(format, a...))
}
3、创建⼀个⾃定义错误。
(三)、⾃定义错误
1、实现步骤
1、定义⼀个结构体,表示⾃定义错误的类型
2、让⾃定义错误类型实现error接⼝的⽅法 :Error() string
3、定义⼀个返回error的函数。根据程序实际功能⽽定。
2、示例代码:
package main
import (
"fmt"
"time"
)
//1.定义⼀个结构体,表示⾃定义错误的类型
type MyError struct {
When time.Time
What string
}
//2、⾃定义错误类型实现error接⼝的⽅法 :Error() string
func (e *MyError) Error() string {
return fmt.Sprintf("%v : %v", e.When, e.What)
}
//3.定义⼀个返回error的函数。求矩形的⾯积
func getArea(width, length float64) (float64, error) {
errorMsg := ""
if width < 0 && length < 0 {
errorMsg = fmt.Sprintf("⻓度:%v ,宽度:%v ,均为负数", length,
width)
} else if length < 0 {
errorMsg = fmt.Sprintf("⻓度:%v ,出现负数", length)
} else if width < 0 {
errorMsg = fmt.Sprintf("宽度:%v ,出现负数", width)
}
if errorMsg != "" {
return 0, &MyError{time.Now(), errorMsg}
} else {
return width * length, nil
}
}
func main() {
res1, err := getArea(-4, -6)
if err != nil {
fmt.Printf(err.Error())
} else {
fmt.Println("⾯积是:", res1)
}
}