go语言中没有类似python的Try...except机制,如果遇到可能会发生未知错误的处理中,因为无法提前覆盖所有异常,会导致运行中产生panic程序退出,其实在循环中利用recover的联动机制,把for循环处理的内容放到匿名函数中,以下为示例(其实可以把任意一块你觉得可能会有未知错误的地方放在匿名函数中即可):
package main
import (
"fmt"
)
func main() {
i := 0
detail := make(map[int]string)
for ; i <= 10; i++ {
func() {
defer func() {
if p := recover(); p != nil {
fmt.Printf("panic recover! p: %#v\n", p)
detail[i] = "panic"
}
}()
if i > 2 && i < 5 || i > 8 {
panic(fmt.Errorf("raise panic when i==%v\n", i))
} else {
fmt.Printf("pass through %v normally.\n", i)
detail[i] = "normal"
}
}()
}
fmt.Printf("final detail:\n%#v", detail)
}