Go Wiki: PanicAndRecover
目录
Panic
panic
和 recover
函数在某些其他语言中类似于异常的 try/catch,因为 panic
会导致程序堆栈开始展开,而 recover
可以阻止它。延迟的函数在堆栈展开时仍会被执行。如果在这种延迟函数中调用 recover
,堆栈展开将停止,并且 recover
会返回传递给 panic
的值(作为 interface{}
)。在非正常情况下,例如数组或切片越界索引,运行时也会 panic。如果 panic
导致堆栈展开到任何正在执行的 goroutine 之外(例如,main
或传递给 go
的顶层函数未能从中恢复),程序将退出,并附带所有正在执行的 goroutines 的堆栈跟踪。一个 goroutine 中的 panic
不能被另一个 goroutine recover
。
包中的用法
根据惯例,不应允许显式的 panic()
跨越包边界。应通过返回错误值来向调用者指示错误情况。然而,在包内部,尤其是在对非导出函数进行深度嵌套调用时,使用 panic 来指示应该转换为错误并返回给调用函数的错误情况可能非常有用(并提高可读性)。下面是一个不算巧妙的例子,说明了一个嵌套函数和一个导出函数可能通过这种基于 panic 的错误关系进行交互。
// A ParseError indicates an error in converting a word into an integer.
type ParseError struct {
Index int // The index into the space-separated list of words.
Word string // The word that generated the parse error.
Error error // The raw error that precipitated this error, if any.
}
// String returns a human-readable error message.
func (e *ParseError) String() string {
return fmt.Sprintf("pkg: error parsing %q as int", e.Word)
}
// Parse parses the space-separated words in input as integers.
func Parse(input string) (numbers []int, err error) {
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
err = fmt.Errorf("pkg: %v", r)
}
}
}()
fields := strings.Fields(input)
numbers = fields2numbers(fields)
return
}
func fields2numbers(fields []string) (numbers []int) {
if len(fields) == 0 {
panic("no words to parse")
}
for idx, field := range fields {
num, err := strconv.Atoi(field)
if err != nil {
panic(&ParseError{idx, field, err})
}
numbers = append(numbers, num)
}
return
}
为了演示这种行为,请考虑以下 main 函数
func main() {
var examples = []string{
"1 2 3 4 5",
"100 50 25 12.5 6.25",
"2 + 2 = 4",
"1st class",
"",
}
for _, ex := range examples {
fmt.Printf("Parsing %q:\n ", ex)
nums, err := Parse(ex)
if err != nil {
fmt.Println(err)
continue
}
fmt.Println(nums)
}
}
参考
此内容是 Go Wiki 的一部分。