码迷,mamicode.com
首页 > 编程语言 > 详细

Go语言中异常处理painc()和recover()的用法

时间:2016-03-08 21:12:12      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

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

  

 

Go语言中异常处理painc()和recover()的用法

标签:

原文地址:http://www.cnblogs.com/songxingzhu/p/5255485.html

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