Go 错误处理

if err != nil

一、处理方式

发出错误:

1
2
3
4
5
6
func Sqrt(f float64) (float64, error) {
if f < 0 {
return 0, errors.New("math: square root of negative number")
}
// ...
}

处理错误:

1
2
3
4
result, err:= Sqrt(-1)
if err != nil {
// ...
}

二、争议

1. 负面意见

2. 正面意见

  • 保持了 Go 的简洁,避免 try、catch、finally 等额外语法的引入
  • 从语言层面上要求程序员正视和处理每一个错误,而非像 Java 一样,开发者可以无脑往上抛

3. 官方说法

Why does Go not have exceptions?

We believe that coupling exceptions to a control structure, as in the try-catch-finally idiom, results in convoluted code. It also tends to encourage programmers to label too many ordinary errors, such as failing to open a file, as exceptional.

Go takes a different approach. For plain error handling, Go’s multi-value returns make it easy to report an error without overloading the return value. A canonical error type, coupled with Go’s other features, makes error handling pleasant but quite different from that in other languages.

Go also has a couple of built-in functions to signal and recover from truly exceptional conditions. The recovery mechanism is executed only as part of a function’s state being torn down after an error, which is sufficient to handle catastrophe but requires no extra control structures and, when used well, can result in clean error-handling code.

See the Defer, Panic, and Recover article for details. Also, the Errors are values blog post describes one approach to handling errors cleanly in Go by demonstrating that, since errors are just values, the full power of Go can be deployed in error handling.

Why does Go not have exceptions

参考