码迷,mamicode.com
首页 > 其他好文 > 详细

panic 和 recover的区别

时间:2019-11-11 00:21:53      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:指针   http   ima   main   报告   imp   结果   mamicode   value   

panic:

1.报告致命错误的一种方式,如:数组访问越界,空指针引用等。
2.panic异常发生时,程序会中断运行。

import "fmt"

func testa() {
	fmt.Println("aaaaaaaaa")
}

func testb(i int) {
	fmt.Println("bbbbbbbbb")
	arr := [10]int{}
	// var arr [10]int
	arr[i] = 123
	// panic("this is a panic test")
}

func testc() {
	fmt.Println("ccccccccc")
}

func main() {
	testa()
	testb(10)
	testc()
}

结果:

技术图片

recover:

panic异常一旦被引发就会导致程序崩溃。
所以Go语言提供了专用于“拦截”运行时panic的内建函数—recover。
它可以使当前程序从panic的状态中恢复,重新获得流程控制权,并返回panic value。
在未发生panic时调用recover,recover会返回nil。

注意:recover只有在defer调用的函数中有效。

import "fmt"

func testb(x int) {
	defer func() {
		// recover()
		// fmt.Println(recover())
		if err := recover(); err != nil {
			fmt.Println("err 是:", err)
		}
	}()
	var a [10]int
	a[x] = 123
}

func testc() {
	fmt.Println("ccccccccccc")
}

func main() {
	testb(11)
	testc()
}

结果:

技术图片

 

以上。

panic 和 recover的区别

标签:指针   http   ima   main   报告   imp   结果   mamicode   value   

原文地址:https://www.cnblogs.com/jianyingjie/p/11832326.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!