异常处理是程序健壮性的关键,往往开发人员的开发经验的多少从异常部分处理上就能得到体现。如何适度的添加异常,往往是整个产品体验成败的关键。 Go语言中没有Try Catch Exception机制,但是提供了panic-and-recover机制。
本示例主要说明如何捕获异常,先来模拟一种异常情况,在一些项目中,经常有数组下标越界的情况,我们来人为构造一下
package main
import "fmt"
func MyPanic() {
fmt.Println("Running in MyPanic...")
var a[]int
a[3] = 5
}
func main() {
MyPanic()
}此时运行程序,很明显会出现如下问题:
Running in MyPanic...
panic: runtime error: index out of range [3] with length 0
goroutine 1 [running]:
main.MyPanic()
/root/workspace/go/test_panic_recover_basic.go:14 +0x5e
main.main()
/root/workspace/go/test_panic_recover_basic.go:18 +0x17
exit status 2尝试用recover进行异常处理
package main
import "fmt"
func MyPanic() {
defer func() {
if x := recover(); x != nil {
fmt.Printf("[ERROR]: My panic handle error: %s
", x)
}
}()
fmt.Println("Running in MyPanic...")
var a[]int
a[3] = 5
}
func main() {
MyPanic()
}就上面的代码进行一下分析:
Running in MyPanic...
[ERROR]: My panic handle error: runtime error: index out of range [3] with length 0本示例除了介绍panic(),还实现了一种统一的ErrorHandler方法(有点像Python中的装饰器),来统一处理函数的异常
package main
import "fmt"
func ErrorHandler(f func()) (b bool) {
defer func() {
if x := recover(); x != nil {
fmt.Printf("[ERROR]Handle error here: %s
", x)
b = true
}
}()
f()
return
}
func CallPanic() {
panic("Call panic")
}
func main() {
fmt.Println(ErrorHandler(CallPanic))
}我们来对代码进行一下分析:
| 留言与评论(共有 0 条评论) “” |