Files
the-way-to-go_ZH_CN/eBook/13.1.md
2015-11-05 00:08:47 +08:00

69 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 13.1 错误处理
Go 有一个预先定义的 error 接口类型
```go
type error interface {
Error() string
}
```
错误值用来表示异常状态;我们可以在 5.2 节中看到它的标准用法。处理文件操作的例子可以在 12 章找到;我们将在 15 章看到网络操作的例子。errors 包中有一个 errorString 结构体实现了 error 接口。当程序处于错误状态时可以用 `os.Exit(1)` 来中止运行。
## 13.1.1 定义错误
任何时候当你需要一个新的错误类型,都可以用 `errors`(必须先 import包的 `errors.New` 函数接收合适的错误信息来创建,像下面这样:
```go
err := errors.New(math - square root of negative number)
```
在示例 13.1 中你可以看到一个简单的用例:
示例 13.1 [errors.go](examples/chapter_13/errors.go)
```go
// errors.go
package main
import (
"errors"
"fmt"
)
var errNotFound error = errors.New("Not found error")
func main() {
fmt.Printf("error: %v", errNotFound)
}
// error: Not found error
```
可以用于计算平方根函数的参数测试:
```go
func Sqrt(f float64) (float64, error) {
if f < 0 {
return 0, errors.New (math - square root of negative number)
}
// implementation of Sqrt
}
```
你可以像下面这样调用这个函数:
```go
if f, err := Sqrt(-1); err != nil {
fmt.Printf(Error: %s\n, err)
}
```
由于 `fmt.Printf` 会自动调用 `String()` 方法 (参见 10.7 节所以错误信息“Error: math - square root of negative number”会打印出来。通常错误信息都会有像“Error:”这样的前缀,所以你的错误信息不要以大写字母开头。