Go语言中异常处理painc()和recover()的用法
2016-03-08 20:31
351 查看
Go语言中异常处理painc()和recover()的用法
1、Painc用法是:用于抛出错误。Recover()用法是:将Recover()写在defer中,并且在可能发生panic的地方之前,先调用此defer的东西(让系统方法域结束时,有代码要执行。)当程序遇到panic的时候(当然,也可以正常的调用出现的异常情况),系统将跳过后面的代码,进入defer,如果defer函数中recover(),则返回捕获到的panic的值。2、代码:
package main import "fmt" func main() { fmt.Printf("hello world my name is %s, I'm %d\r\n", "songxingzhu", 26) defer func() { if err := recover(); err != nil { fmt.Println("出了错:", err) } }() myPainc() fmt.Printf("这里应该执行不到!") } func myPainc() { var x = 30 var y = 0 //panic("我就是一个大错误!") var c = x / y fmt.Println(c) }
3、执行结果:
Atom Runner: main.go hello world my name is songxingzhu, I'm 26 出了错: runtime error: integer divide by zero Exited with code=0 in 1.667 seconds
相关文章推荐
- Google浏览器开发者工具 快捷键
- CodeForces 132C Logo Turtle (记忆化搜索)
- altium designer中如何添加logo
- category中添加属性的简单方式
- 在mingw项目中引入googletest
- LightOJ 1259 - Goldbach`s Conjecture (分解偶数为两个素数之和)
- Codeforces--630D--Hexagons(规律)
- Codeforces--630D--Hexagons(规律)
- MIGO相关的3个BADI增强点
- 从google的DrawerLayout来看看scroller的使用方法
- django用户认证
- 设置多图片表good_pic(中的商品id)为外键.参考goods商品表中的id,在删除商品的时候.一起删除多图片.
- Got fatal error 1236 from master when reading data from binary log: ‘Slave can not handle replicatio
- 【Google 重磅突破】相比LSTM,NLP 关键任务提升 20%
- codeforces 598D - Igor In the Museum
- django --fields.E304 错误解决方案
- django学习笔记(1)环境搭建
- 使用Leangoo玩转故事地图
- Howto run google-chrome as root
- 通过接口实现压缩文件、目录,修正遍历方式,未添加排除文件操作