go中异常处理

go中异常处理

一、简介

这里介绍使用defer、panic、recover进行异常处理。

二、使用

2.1 defer

defer是go语言中的关键字,延迟指定函数的执行。通常在资源释放、连接关闭、函数结束时调用。多个defer为堆栈结构,先进后出,也就是先进的后执行。defer可用于异常抛出后的处理。

2.2 panic

panic是go语言中的内置函数,抛出异常(类似java中的throw)。其函数定义为:

func panic(v interface{})
2.3 recover

recover() 是go语言中的内置函数,获取异常(类似java中的catch),多次调用时,只有第一次能获取值。其函数定义为:

func recover() interface{}

三、示例

借助defer(异常时函数结束返回)、panic(自定义抛出异常)、recover(获取异常)进行异常处理。示例如下:

package main

import "fmt"

//panic()  内置函数,抛出异常
//定义如下:func panic(v interface{})
//制造异常
func make_exception() {
	fmt.Println("make exception")
	//抛出异常
	panic("exception a")
	fmt.Println("end make exception") //不会执行(因前面抛出了异常,中断了程序的执行)
}

//recover() 内置函数,获取异常,多次调用,只有第一次能获取值
//定义如下:func recover() interface{}
//捕获异常方法一
func catch_exception_first() {
	fmt.Println("start catch_exception_first")
	err := recover() //获取异常
	if err != nil {
		fmt.Println("dispose first: " + fmt.Sprintf("%s", err))
	}
	fmt.Println("end catch_exception_first")
}

//捕获异常方法二
func catch_exception_second() {
	fmt.Println("start catch_exception_second")
	err := recover() //获取异常
	if err != nil {
		fmt.Println("dispose second: " + fmt.Sprintf("%s", err))
	}
	fmt.Println("end catch exception second")
}

//含有异常的方法
func invoke_exception_test() {
	fmt.Println("start invoke_exception_test")

	//defer 在资源释放、连接关闭、函数结束时调用,多个defer为堆栈结构,先进后出,也就是先进的后执行
	defer catch_exception_first()  //异常处理方法一,根据堆栈原理,先入栈,后执行,异常已经被异常处理方法二捕获,故不能再次捕获异常
	defer catch_exception_second() //异常处理方法二,根据堆栈原理,后入栈,先执行,能捕获异常
	//抛出异常
	make_exception()
	make_exception()                         //不会执行(因前面抛出了异常,中断了程序的执行)
	fmt.Println("end invoke_exception_test") //不会执行(因前面抛出了异常,中断了程序的执行)
}

//普通方法
func normal_method() {
	fmt.Println("start normal_method")
	invoke_exception_test()
	fmt.Println("end normal_method")
}

//main方法
func main() {
	fmt.Println("start main")
	normal_method()
	fmt.Println("end main")
}

输出:

start main
start normal_method
start invoke_exception_test
make exception
start catch_exception_second
dispose second: exception a
end catch exception second
start catch_exception_first
end catch_exception_first
end normal_method
end main
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值