在go中,当程序出现异常时,会发生panic。当发生panic后,需要使用recover捕获,如果没有捕获,则程序退出。
package main
import "fmt"
import "runtime/debug"
func fun() {
fmt.Println("fun begin")
defer func() {
//捕获panic
if err := recover(); err != nil {
debug.PrintStack()
//获取堆栈信息的字符串
fmt.Println("xxx", string(debug.Stack()))
}
}()
var p *int
//产生异常
*p = 0
fmt.Println("fun end")
//这里不执行
for {}
}
func main() {
fmt.Println("main begin")
fun()
//因为panic被recover捕获,所以下面继续执行
fmt.Println("main end")
for {}
}
输出结果:
main begin
fun begin
goroutine 1 [running]:
runtime/debug.Stack(0xc000088060, 0xc00009a000, 0xa)
/usr/local/Cellar/go/1.11.1/libexec/src/runtime/debug/stack.go:24 +0xa7
runtime/debug.PrintStack()
/usr/local/Cellar/go/1.11.1/libexec/src/runtime/debug/stack.go:16 +0x22
main.fun.func1()
/Users/xxx/test/a.go:10 +0x46
panic(0x10a9760, 0x115d520)
/usr/local/Cellar/go/1.11.1/libexec/src/runtime/panic.go:513 +0x1b9
main.fun()
/Users/xxx/test/a.go:16 +0x7f
main.main()
/Users/xxx/test/a.go:24 +0x66
xxx goroutine 1 [running]:
runtime/debug.Stack(0xc00007ada8, 0x10a9760, 0x115d520)
/usr/local/Cellar/go/1.11.1/libexec/src/runtime/debug/stack.go:24 +0xa7
main.fun.func1()
/Users/xxx/test/a.go:11 +0x4b
panic(0x10a9760, 0x115d520)
/usr/local/Cellar/go/1.11.1/libexec/src/runtime/panic.go:513 +0x1b9
main.fun()
/Users/xxx/test/a.go:16 +0x7f
main.main()
/Users/xxx/test/a.go:24 +0x66
main end
产生panic异常如果使函数返回结果
package main
import "fmt"
func test() int {
defer func() {
if err := recover(); err != nil {
//针对匿名函数可以,这里不行
return 1
}
}()
var p *int
*p = 0
return 0
}
func main() {
fmt.Println("ret is", test())
for {}
}
结果
# command-line-arguments
./test.go:8:4: too many arguments to return
have (number)
want (
下面这种方法可以
package main
import "fmt"
func test() (a int) {
defer func() {
if err := recover(); err != nil {
//给返回变量赋值
a = 1
}
}()
var p *int
*p = 0
return 0
}
func main() {
fmt.Println("ret is", test())
for {}
}
结果
ret is 1
来源:CSDN
作者:enjoy嚣士
链接:https://blog.csdn.net/u013919153/article/details/88415454