英文源地址
通过使用内置的recover函数, 使得Go从panic中恢复成为可能. recover可以阻止因panic而终止程序, 而是让程序继续执行.
这里有一个例子可以说明这是很有用的: 如果一个客户端连接出现严重错误, 服务器不希望崩溃.相反, 服务器希望关闭该链接并继续为其他客户端提供服务.事实上, 这就是Go的net/http包默认为HTTP服务器所做的.
package main
import "fmt"
// panic函数
func mayPanic() {
panic("a problem")
}
// recover必须在defer函数中调用
// 当封闭函数出现panic时, 将激活defer, 并且其中的recover调用将捕获panic
func main() {
defer func() {
// recover的返回值时调用panic时引发的错误
if r := recover(); r != nil {
fmt.Println("Recovered. Error:\n", r)
}
}()
mayPanic()
// 这段代码不会运行, 因为mayPanic会产生panic.
// main函数的执行在panic点停止, 并在defer闭包中继续执行.
fmt.Println("After mayPanic()")
}
$ go run recover.go
Recovered. Error:
a problem
下一节将介绍: 字符串函数