当前位置:网站首页>Go panic and recover
Go panic and recover
2022-07-28 08:54:00 【go|Python】
List of articles
go panic And recover
go Unlike python equally , Yes try-except grammar , The method of exception capture is also not recommended , It's the way to return the exception directly , And it will be more convenient to exit directly than to return layer by layer . therefore go Implemented in the panic- recover Mechanism . It is specially used to throw and recover these exceptions . however stay go It is more recommended to use Wrong type , instead of Use panic and recover. Only when the program cannot continue to run , Should use panic-recover Mechanism .
panic
panic For active throwing of exceptions , Be similar to python Medium raise
panic There are two reasonable use cases .
An unrecoverable error occurred , The program cannot continue at this time . One example is web The server was unable to bind the required port . under these circumstances , You should use panic, Because if you can't bind the port , Nothing can be done .
A programming error has occurred . Let's say we have a way to receive pointer parameters , And others use it
nilIt is called as an argument . under these circumstances , We can use panic, Because this is a programming error : usenilParameter called a method that can only receive legal pointers .
Example
func main() {
fmt.Println(" I started a ")
panic(" I made a mistake ")
fmt.Println(" I'm finished ")
}

recover
recover Used to restore program operation , however recover The correct use of 2 Point needs attention
- recover Must cooperate defer Use
- recover Must be in defer The first layer under closures or calling functions uses
Example
func main() {
fmt.Println(" I started a ")
// recover() // No error is reported during execution , So it doesn't work
defer func() {
// Use... Correctly 1
recover()
}()
// defer Test4() // Use... Correctly 2
panic(" I made a mistake ")
// recover() // After reporting an error, it cannot be implemented here , So it doesn't work
fmt.Println(" I'm finished ")
}
func Test4() {
recover()
}

It should be noted that ,recover It can resume the operation of the program , however This floor The subsequent code of will not be executed . The function or method will be skipped directly , Execute other code
func main() {
f1()
f2()
f3()
}
func Test4() {
recover()
}
func f1() {
fmt.Println(" I am a f1")
}
func f2() {
defer Test4() // Use... Correctly 2
panic("f2 Wrong report ")
fmt.Println(" I am a f2")
}
func f3() {
fmt.Println(" I am a f3")
}

go Exception handling template in
contrast python Medium try-except-finallly, stay go We can also use recover + defer + if The way of judgment , The code is as follows :
defer func() {
if err := recover(); err != nil {
fmt.Println(err) // Type of printing error , python in except The code in
}
fmt.Println("python in finally Code for ")
}
Put this code , Just put it above the code that may go wrong , Of course, you can also write the above correct use 2, To use .
边栏推荐
- bash-shell 免交互
- Gbase 8A MPP and Galaxy Kirin (x86 version) complete deep adaptation
- The five pictures tell you: why is there such a big gap between people in the workplace?
- Vrrp+mstp configuration details [Huawei ENSP experiment]
- Wechat applet - wechat applet browsing PDF files
- 为什么 ThreadLocal 可以做到线程隔离?
- Starfish Os打造的元宇宙生态,跟MetaBell的合作只是开始
- Warehouse of multiple backbone versions of yolov5
- Sparksql and flinksql create and link table records
- Can‘t connect to server on ‘IP‘ (60)
猜你喜欢

Chapter 2-14 sum integer segments

Explain cache consistency and memory barrier

I am a 27 year old technical manager, whose income is too high, and my heart is in a panic

A new method of exposing services in kubernetes clusters

C #, introductory tutorial -- debugging skills and logical error probe technology and source code when the program is running

竞赛:糖尿病遗传风险检测挑战赛(科大讯飞)

GBase 8a MPP与银河麒麟(x86版)完成深度适配

Flink window & time principle

Customer first | domestic Bi leader, smart software completes round C financing

Export SQL server query results to excel table
随机推荐
Data fabric, next air outlet?
Recruiting talents, gbase high-end talent recruitment in progress
Why setting application.targetframerate doesn't work
Analysis of model predictive control (MPC) (IX): numerical solution of quadratic programming (II)
SQL injection - pre Foundation
I use SqlClient normally, and dlink submission will report this error. What should I do?
PostgreSQL:无法更改视图或规则使用的列的类型
微服务架构 Sentinel 的服务限流及熔断
第2章-2 计算分段函数[1]
Image batch processing | necessary skills
When unity switches to another scene, he finds that the scene is dimmed
Redis basic knowledge, let's review it
Alibaba technology has four sides + intersection +hr, and successfully got the offer. Can't double non undergraduate students enter the big factory?
Two dimensional array and operation
GB/T 41479-2022信息安全技术 网络数据处理安全要求 导图概览
How to import and export Youxuan database
1299_ Task status and switching test in FreeRTOS
Source code analysis of linkedblockingqueue
Detailed explanation of DHCP distribution address of routing / layer 3 switch [Huawei ENSP]
Machine learning how to achieve epidemic visualization -- epidemic data analysis and prediction practice