当前位置:网站首页>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
边栏推荐
- How to refresh the opening amount of Oracle ERP
- Processing of tree structure data
- [error record] an error is reported in the fluent interface (no mediaquery widget ancestor found. | scaffold widgets require a mediaquery)
- Rockchip3399 start auto load driver
- 小程序开发的部分功能
- "Jetpack - livedata parsing"
- [shutter] hero animation (hero realizes radial animation | hero component createrecttween setting)
- 浏览器是如何对页面进行渲染的呢?
- stm32F407-------DMA
- Leetcode(540)——有序数组中的单一元素
猜你喜欢
Introduction to kotlin collaboration
Bottleneck period must see: how can testers who have worked for 3-5 years avoid detours and break through smoothly
"Jetpack - livedata parsing"
NCTF 2018 part Title WP (1)
Introduce in detail how to communicate with Huawei cloud IOT through mqtt protocol
[Appendix 6 Application of reflection] Application of reflection: dynamic agent
In the face of difficult SQL requirements, HQL is not afraid
Technology sharing | Frida's powerful ability to realize hook functions
微信小程序开发工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理问题
How can retail enterprises open the second growth curve under the full link digital transformation
随机推荐
【Camera专题】HAL层-addChannel和startChannel简析
Network security NAT network address translation
树形结构数据的处理
我的创作纪念日
Processing of tree structure data
Huakaiyun (Zhiyin) | virtual host: what is a virtual host
Missing library while loading shared libraries: libisl so. 15: cannot open shared object file: No such file
微信小程序開發工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理問題
[camera topic] complete analysis of camera dtsi
【Camera专题】Camera dtsi 完全解析
Niuniu's ball guessing game (dynamic planning + prefix influence)
Solution for processing overtime orders (Overtime unpaid)
Button button adaptive size of wechat applet
[leetcode] 797 and 1189 (basis of graph theory)
缺少库while loading shared libraries: libisl.so.15: cannot open shared object file: No such file
Where is the future of test engineers? Confused to see
NCTF 2018 part Title WP (1)
Network security - virus
Redis: simple use of redis
[AUTOSAR cantp] -2.11-uds diagnostic response frame data segment data padding data filling and data optimization data optimization (Theory + configuration)