当前位置:网站首页>Use go language to realize try{}catch{}finally
Use go language to realize try{}catch{}finally
2022-07-03 02:05:00 【ZWZhangYu】
Example
Java Development must be familiar try{}catch{}finally, In the use of Go Before language implementation , We need to figure out the three-step process first :
【1】 Execute first try Code block , And then there was catch Code block , The second is finally Code block
【2】catch Will be in try Execute when an exception occurs in the code block , It is often used to catch exceptions and rollback transactions
【3】 The three code blocks are independent of each other , Internally declared object variables are not shared
package exception
import "fmt"
// Defining structure
type TcfBlock struct {
Try func()
Catch func(interface{
})
Finally func()
}
// Build an overall execution process , Similar to the design of template method
func (b TcfBlock) Do() {
fmt.Println(" perform Do")
if b.Finally != nil {
defer b.Finally()
}
if b.Catch != nil {
defer func() {
if e := recover(); e != nil {
b.Catch(e)
}
}()
}
b.Try()
}
It defines TcfBlock The structure of the body , There are three functions in the structure , These three functions correspond to try{}catch{}finally Three steps of , In the following Do Method constructs the execution process of three functions , Equivalent to template method design , Define Architecture .
package main
import (
"fmt"
"practise/error/transaction/component"
)
// test try{}catch{}finally Components
func main() {
component.TcfBlock{
Try: func() {
fmt.Println(" perform Try Code ")
testError()
},
Catch: func(e interface{
}) {
testCatch(e)
},
Finally: func() {
fmt.Println(" perform Finally Code ")
},
}.Do()
}
func testCatch(e interface{
}) {
fmt.Println(" perform Catch Code ")
}
func testError() {
panic(" Simulate anomalies ")
}
analysis
【1】Recover It's a Go Built in functions of language , You can let people who are in the process of downtime goroutine Come back ,recover Only in the delay function defer Effective in , In the normal course of execution , call recover Returns the nil And nothing else , If the current goroutine panic , call recover You can capture panic The input value of , And resume normal execution . above Catch In the code if e := recover(); e != nil It is through recover() To capture panic(“ Simulate anomalies ”) It's abnormal . Here we need to pay attention to Go Exceptions in are handled through the return value , We need to deal with it according to the actual situation and throw an exception .
【2】goLang If there are more than one code block defer, Then follow the order of last in first out , Stack like data structure , Using this feature, we can achieve catch and Finally Of defer Execution order , Realization Finally stay catch Carry out later , And it can ensure that both will be implemented .
【3】 Using the above implementation try{}catch{}finally Component is applicable to database transaction operations , Multiple data operations can be placed in try Inside and in catch Capture exception , Then determine whether the transaction is committed or rolled back .
【4】 Refer to the component design above , It can realize some functional processes of fixed template architecture , In this way, the overall code looks clearer
边栏推荐
- Storage basic operation
- [shutter] shutter debugging (debugging control related functions | breakpoint management | code operation control)
- Anna: Beibei, can you draw?
- 树形结构数据的处理
- Ni visa fails after LabVIEW installs the third-party visa software
- Niuniu's ball guessing game (dynamic planning + prefix influence)
- 机器学习笔记(持续更新中。。。)
- 深度(穿透)选择器 ::v-deep/deep/及 > > >
- Network security - Trojan horse
- Modify table structure
猜你喜欢
How do it students find short-term internships? Which is better, short-term internship or long-term internship?
深度(穿透)选择器 ::v-deep/deep/及 > > >
[fluent] fluent debugging (debug debugging window | viewing mobile phone log information | setting normal breakpoints | setting expression breakpoints)
In 2022, 95% of the three most common misunderstandings in software testing were recruited. Are you that 5%?
ByteDance data Lake integration practice based on Hudi
《上市风云》荐书——唯勇气最可贵
深度学习笔记(持续更新中。。。)
小程序開發的部分功能
Visual yolov5 format data set (labelme JSON file)
可視化yolov5格式數據集(labelme json文件)
随机推荐
LabVIEW安装第三方VISA软件后NI VISA失效
es6 filter() 数组过滤方法总结
Hard core observation 547 large neural network may be beginning to become aware?
Network security - Information Collection
《上市风云》荐书——唯勇气最可贵
His experience in choosing a startup company or a big Internet company may give you some inspiration
Redis:Redis的简单使用
Network security - DNS spoofing and phishing websites
Introduce in detail how to communicate with Huawei cloud IOT through mqtt protocol
The technology boss is ready, and the topic of position C is up to you
Analysis, use and extension of open source API gateway apisex
Network security - phishing
使用Go语言实现try{}catch{}finally
详细些介绍如何通过MQTT协议和华为云物联网进行通信
How do it students find short-term internships? Which is better, short-term internship or long-term internship?
File class (add / delete)
[shutter] top navigation bar implementation (scaffold | defaulttabcontroller | tabbar | tab | tabbarview)
Huakaiyun | virtual host: IP, subnet mask, gateway, default gateway
easyPOI
Performance test | script template sorting, tool sorting and result analysis