一. 错误
- 在程序执行过程中出现的不正常情况称为错误
Go语言中使用builtin包下error接口作为错误类型,官方源码定义如下
- 只包含了一个方法,方法返回值是string,表示错误信息
// The error built-in interface type is the conventional interface for// representing an error condition, with the nil value representing no error.type error interface {Error() string}
- 只包含了一个方法,方法返回值是string,表示错误信息
Go语言中错误都作为方法/函数的返回值,因为Go语言认为使用其他语言类似try…catch这种方式会影响到程序结构
- 在Go语言标准库的errors包中提供了error接口的实现结构体errorString,并重写了error接口的Error()方法.额外还提供了快速创建错误的函数 ```go 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 }
- 如果错误信息由很多变量(小块)组成,可以借助`fmt.Errorf("verb",...)`完成错误信息格式化,因为底层还是errors.New()```go// 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...))}
二.自定义错误
- 使用Go语言标准库创建错误,并返回
```go
func demo(i, k int) (d int, e error) {
if k == 0 {
} d = i / k return }e = errors.New("初始不能为0")d=0return
func main() { result,error:=demo(6,0) fmt.Println(result,error) }
- 如果错误信息由多个内容组成,可以使用下面实现方式```gofunc demo(i, k int) (d int, e error) {if k == 0 {e = fmt.Errorf("%s%d和%d", "除数不能是0,两个参数分别是:", i, k)d = 0return}d = i / kreturn}func main() {result, error := demo(6, 0)fmt.Println(result, error)}
三.Go语言中错误处理方式
- 可以忽略错误信息,使用占位符
```go
func demo(i, k int) (d int, e error) {
if k == 0 {
} d = i / k return }e = fmt.Errorf("%s%d和%d", "除数不能是0,两个参数分别是:", i, k)d = 0return
func main() { result, _ := demo(6, 0) fmt.Println(result) }
- 使用if处理错误,原则上每个错误都应该解决```gofunc demo(i, k int) (d int, e error) {if k == 0 {e = fmt.Errorf("%s%d和%d", "除数不能是0,两个参数分别是:", i, k)d = 0return}d = i / kreturn}func main() {result, error := demo(6, 0)if error != nil {fmt.Println("发生错误", error)return}fmt.Println("程序执行成功,结果为:", result)}
