当前位置:网站首页>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
边栏推荐
- Where is the future of test engineers? Confused to see
- Performance test | script template sorting, tool sorting and result analysis
- Problems encountered in small program development of dark horse shopping mall
- 树形结构数据的处理
- 【Camera专题】手把手撸一份驱动 到 点亮Camera
- 创建+注册 子应用_定义路由,全局路由与子路由
- Button button adaptive size of wechat applet
- Comment le chef de file gère - t - il l'équipe en cas d'épidémie? Contributions communautaires
- DDL basic operation
- Types of map key and object key
猜你喜欢

Wechat applet Development Tool Post net:: Err Proxy Connexion Problèmes d'agent défectueux

Solution for processing overtime orders (Overtime unpaid)

easyExcel

"Jetpack - livedata parsing"
![[shutter] shutter debugging (debugging fallback function | debug method of viewing variables in debugging | console information)](/img/66/0fda43da0d36fc0c9277ca86ece252.jpg)
[shutter] shutter debugging (debugging fallback function | debug method of viewing variables in debugging | console information)

树形结构数据的处理
![[fluent] fluent debugging (debug debugging window | viewing mobile phone log information | setting normal breakpoints | setting expression breakpoints)](/img/ac/bf83f319ea787c5abd7ac3fabc9ede.jpg)
[fluent] fluent debugging (debug debugging window | viewing mobile phone log information | setting normal breakpoints | setting expression breakpoints)
![[shutter] bottom navigation bar implementation (bottomnavigationbar bottom navigation bar | bottomnavigationbaritem navigation bar entry | pageview)](/img/41/2413af283e8f1db5d20ea845527175.gif)
[shutter] bottom navigation bar implementation (bottomnavigationbar bottom navigation bar | bottomnavigationbaritem navigation bar entry | pageview)

Asian Games countdown! AI target detection helps host the Asian Games!

What are the key points often asked in the redis interview
随机推荐
Stm32f407 ------- IIC communication protocol
The technology boss is ready, and the topic of position C is up to you
Storage basic operation
网络安全-NAT网络地址转换
What are the key points often asked in the redis interview
可視化yolov5格式數據集(labelme json文件)
[leetcode] 797 and 1189 (basis of graph theory)
[camera topic] complete analysis of camera dtsi
[Yu Yue education] reference materials of love psychology of China University of mining and technology
How do it students find short-term internships? Which is better, short-term internship or long-term internship?
502 (bad gateway) causes and Solutions
[camera special topic] Hal layer - brief analysis of addchannel and startchannel
Swift开发学习
Network security - talking about security threats
Method of removing webpage scroll bar and inner and outer margins
Niuniu's ball guessing game (dynamic planning + prefix influence)
详细些介绍如何通过MQTT协议和华为云物联网进行通信
单词单词单词
CFdiv2-Fixed Point Guessing-(区间答案二分)
[camera topic] how to save OTP data in user-defined nodes