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

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

 

一、Painc用法是:用于抛出错误。Recover()用法是:将Recover()写在defer中,而且在可能发生panic的地方以前,先调用此defer的东西(让系统方法域结束时,有代码要执行。)当程序遇到panic的时候(固然,也能够正常的调用出现的异常状况),系统将跳事后面的代码,进入defer,若是defer函数中recover(),则返回捕获到的panic的值。ide

二、代码:函数

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)
}

 

三、执行结果:code

 

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
相关文章
相关标签/搜索