当前位置:网站首页>使用Go语言实现try{}catch{}finally
使用Go语言实现try{}catch{}finally
2022-07-03 01:34:00 【ZWZhangYu】
示例
Java开发肯定都熟悉try{}catch{}finally,在使用Go语言实现前,我们需要先搞清楚这三个步骤的流程:
【1】先执行try代码块,然后是catch代码块,其次是finally代码块
【2】catch会在try代码块发生异常时执行,常用于捕获异常然后回滚事务
【3】三个代码块的内部互相独立,内部声明的对象变量不共享
package exception
import "fmt"
// 定义结构
type TcfBlock struct {
Try func()
Catch func(interface{
})
Finally func()
}
// 构建整体的执行流程,类似于模板方法的设计
func (b TcfBlock) Do() {
fmt.Println("执行Do")
if b.Finally != nil {
defer b.Finally()
}
if b.Catch != nil {
defer func() {
if e := recover(); e != nil {
b.Catch(e)
}
}()
}
b.Try()
}
上面定义了TcfBlock 的结构体,结构体里面有三个函数,这三个函数就对应的try{}catch{}finally的三个步骤,在下面的Do方法中构建了三个函数的执行流程,相当于模板方法设计,定义架构。
package main
import (
"fmt"
"practise/error/transaction/component"
)
// 测试try{}catch{}finally组件
func main() {
component.TcfBlock{
Try: func() {
fmt.Println("执行Try代码")
testError()
},
Catch: func(e interface{
}) {
testCatch(e)
},
Finally: func() {
fmt.Println("执行Finally代码")
},
}.Do()
}
func testCatch(e interface{
}) {
fmt.Println("执行Catch代码")
}
func testError() {
panic("模拟异常")
}

分析
【1】Recover 是一个Go语言的内建函数,可以让进入宕机流程中的 goroutine 恢复过来,recover 仅在延迟函数 defer 中有效,在正常的执行过程中,调用 recover 会返回 nil 并且没有其他任何效果,如果当前的 goroutine 陷入恐慌,调用 recover 可以捕获到 panic 的输入值,并且恢复正常的执行。上面的Catch代码中if e := recover(); e != nil 就是通过recover()来捕获测试代码中panic(“模拟异常”)的异常。这里需要注意Go中异常是通过返回值处理的,我们需要根据实际情况进行处理并抛出异常。
【2】goLang如果一个代码块有多个defer,那么按照后入先出的顺序,类似栈的数据结构,使用该特性可以实现catch和Finally的defer执行顺序,实现Finally在catch后面执行,并且可以保证二者都会执行。
【3】使用上述实现的try{}catch{}finally组件适用于数据库事务操作,可以将多个数据操作放在try里面并在catch捕获异常,然后确定事务提交或者事务回滚。
【4】参考如上的组件设计,可以实现一些固定模板架构的功能流程,这样整体的代码看起来也更加清晰
边栏推荐
- Processing of tree structure data
- [data mining] task 4:20newsgroups clustering
- Smart management of Green Cities: Digital twin underground integrated pipe gallery platform
- Huakaiyun (Zhiyin) | virtual host: what is a virtual host
- 网络安全-扫描
- 网络安全-扫描与密码爆破2
- PS去除水印详解
- Virtual list
- stm32F407-------ADC
- Answers to ten questions about automated testing software testers must see
猜你喜欢

Hard core observation 547 large neural network may be beginning to become aware?
![[error record] an error is reported in the fluent interface (no mediaquery widget ancestor found. | scaffold widgets require a mediaquery)](/img/fd/d862412db43a641537fd67f7910741.jpg)
[error record] an error is reported in the fluent interface (no mediaquery widget ancestor found. | scaffold widgets require a mediaquery)
![[data mining] task 2: mimic-iii data processing of medical database](/img/ad/4e7b253d60b29351e3ef252ee5230f.png)
[data mining] task 2: mimic-iii data processing of medical database

In 2022, 95% of the three most common misunderstandings in software testing were recruited. Are you that 5%?

可视化yolov5格式数据集(labelme json文件)

Wechat applet development tool post net:: err_ PROXY_ CONNECTION_ Failed agent problem

Some functions of applet development

微信小程序开发工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理问题
![[North Asia data recovery] data recovery case of raid crash caused by hard disk disconnection during data synchronization of hot spare disk of RAID5 disk array](/img/2a/98400b0d0b5eda1e52abae30746f2b.jpg)
[North Asia data recovery] data recovery case of raid crash caused by hard disk disconnection during data synchronization of hot spare disk of RAID5 disk array

STM32 - switch of relay control lamp
随机推荐
stm32F407-------DMA
[Yu Yue education] Jiujiang University material analysis and testing technology reference
Network security - Information Collection
Where is the future of test engineers? Confused to see
Modify table structure
STM32 - introduction of external interrupts exti and NVIC
In 2022, 95% of the three most common misunderstandings in software testing were recruited. Are you that 5%?
Network security - scanning and password explosion 2
Network security - firewall
[fluent] fluent debugging (debug debugging window | viewing mobile phone log information | setting normal breakpoints | setting expression breakpoints)
Network security - man in the middle attack
In the face of difficult SQL requirements, HQL is not afraid
【Camera专题】手把手撸一份驱动 到 点亮Camera
Anna: Beibei, can you draw?
DDL basic operation
Niuniu's ball guessing game (dynamic planning + prefix influence)
mysql
"Jetpack - livedata parsing"
Everything file search tool
网络安全-浅谈安全威胁