golang实现try-catch-finally机制

面向对象的编程语言往往都会支持语言级别的异常处理,比如c++使用关键字try开始异常语句块, catch捕获异常,throw抛出异常:

try {
	throw 1;
	throw std::logic_error("user defined exception");
} catch (int e) {
	std::clog << e << std::endl;
} catch (const std::exception& e) {
	std::clog << e.what() << std::endl;
} catch (...) {
	std::clog << "finally" << std::endl;
}

而golang的异常机制是:用panic抛出异常,然后在defer中调用recover()捕获异常。
怎么样在golang中实现类似try-catch的异常捕获机制呢?

这里提供一种简单的实现,使用Try函数开启异常捕获,Catch注册异常处理函数:

package try

import "reflect"

// Try catches exception from f
func Try(f func()) *tryStruct {
	return &tryStruct{
		catches: make(map[reflect.Type]ExeceptionHandler),
		hold:    f,
	}
}

// ExeceptionHandler handle exception
type ExeceptionHandler func(interface{})

type tryStruct struct {
	catches map[reflect.Type]ExeceptionHandler
	hold    func()
}

func (t *tryStruct) Catch(e interface{}, f ExeceptionHandler) *tryStruct {
	t.catches[reflect.TypeOf(e)] = f
	return t
}

func (t *tryStruct) Finally(f func()) {
	defer func() {
		if e := recover(); nil != e {
			if h, ok := t.catches[reflect.TypeOf(e)]; ok {
				h(e)
			}
		
			f()
		}
	}()

	t.hold()
}

每次Catch注册异常处理函数需要传入一个具体值 + ExceptionHandler,即可捕获具体值对应类型的异常。
调用代码如下:

import (
	"log"
	"try"
)

func main() {
	try.Try(func() {
		panic("123")
	}).Catch(1, func(e interface{}) {
		log.Println("int", e)
	}).Catch("", func(e interface{}) {
		log.Println("string", e)
	}).Finally(func() {
		log.Println("finally")
	})
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值