当前位置:网站首页>Go language foundation ----- 09 ----- exception handling (error, panic, recover)
Go language foundation ----- 09 ----- exception handling (error, panic, recover)
2022-07-03 07:37:00 【Mango sauce】
1 error
1.1 error About
error It usually deals with some relatively low-level errors , It will not cause program interruption or downtime . Here is go Source code error Related content of :
// Interface definition
type error interface{
Error() string
}
package errors
// Wrong structure definition
type errorString struct{
text string
}
// The errorString Implementation of the method of structure
func (e *errorString)Error() string{
return e.text
}
// Finally, you can get a through this function errorString structure , So that you can call Error Method .
func New(text string) error{
return &errorString(text)
}
For example, simply use two error functions of the standard library :
package main
import (
"errors"
"fmt"
)
func main(){
err1 := fmt.Errorf("%s", "this is a Errorf")
fmt.Println("err1: ", err1)
err2 := errors.New("this New error")
fmt.Println("err2: ", err2)
}

1.2 error Common usage
package main
import (
"errors"
"fmt"
)
// error by nil Explain normal , Otherwise, the report will be wrong , Information from errors.New obtain
func MyDiv(a, b int) (result int, err error){
err = nil
if b == 0 {
err = errors.New(" The denominator cannot be 0")
}else{
result = a/b
}
return // Equivalent to return result, err
}
func main(){
ret, err := MyDiv(2, 2)
if err == nil{
fmt.Println("ret = ", ret)
}else{
fmt.Println(" Expression has illegal value , err: ", err)
}
ret, err = MyDiv(2, 0)
if err == nil{
fmt.Println("ret = ", ret)
}else{
fmt.Println(" Expression has illegal value , err: ", err)
}
}

2 panic
- 1)panic It is usually called when a fatal error occurs , For example, the array is out of bounds , Null pointer, etc , Of course, we can also manually call panic() Function to trigger . similar C Linguistic assert() Assertion function .
2.1 Show manual call panic
package main
import "fmt"
func testa(){
fmt.Println("aaaaaaaaaaaaaa")
}
func testb(){
//fmt.Println("bbbbbbbbbbbbbb")
// Manual call panic() Will trigger an assertion
panic("manual triggered assertions, the program breaks")
}
func testc(){
fmt.Println("ccccccccccccccc")
}
func main(){
testa()
testb()
testc()
}
The relevant errors are as follows :
2.2 Array out of bounds, resulting in panic
package main
import "fmt"
func testa(){
fmt.Println("aaaaaaaaaaaaaa")
}
func testb(index int){
//fmt.Println("bbbbbbbbbbbbbb")
// Manual call panic() Will trigger an assertion
// panic("manual triggered assertions, the program breaks")
// Array out of bounds, resulting in panic Assertion
var x [10]int
fmt.Println("x: ", x[index])
}
func testc(){
fmt.Println("ccccccccccccccc")
}
func main(){
testa()
testb(10) // Array out of bounds triggers assertion
testc()
}

3 recover function
Happen when panic When it's wrong , It interrupts the program , But sometimes we don't want the program to break , We can use recover Function to capture this interrupt .
But notice :
- 1)recover() Only in defer The function called is valid . When defer, And this function happens panic error , Then the error will be caught , The program will return to normal .
for example :
package main
import "fmt"
func testa(){
fmt.Println("aaaaaaaaaaaaaa")
}
func testb(index int){
//fmt.Println("bbbbbbbbbbbbbb")
// Manual call panic() Will trigger an assertion
// panic("manual triggered assertions, the program breaks")
// Set up recover
defer func() {
if err := recover(); err != nil{
//fmt.Println("errInfo: ", recover())// Don't call... Again recover() As information , Because the call is normal at this time ,
// Because there are no mistakes , The error is already in if Caught in
fmt.Println("errInfo: ", err)
}
}()
// Array out of bounds, resulting in panic Assertion
var x [10]int
fmt.Println("x: ", x[index])
}
func testc(){
fmt.Println("ccccccccccccccc")
}
func main(){
testa()
testb(10) // Array out of bounds triggers assertion
testc()
}

边栏推荐
- 【MySQL 13】安装MySQL后第一次修改密码,可以可跳过MySQL密码验证进行登录
- PAT甲级 1032 Sharing
- TypeScript let与var的区别
- 【MindSpore论文精讲】AAAI长尾问题中训练技巧的总结
- SQL create temporary table
- UA camouflage, get and post in requests carry parameters to obtain JSON format content
- HISAT2 - StringTie - DESeq2 pipeline 进行bulk RNA-seq
- 技术干货|昇思MindSpore NLP模型迁移之Roberta ——情感分析任务
- The babbage industrial policy forum
- Analysis of the problems of the 7th Blue Bridge Cup single chip microcomputer provincial competition
猜你喜欢

技术干货|百行代码写BERT,昇思MindSpore能力大赏

图像识别与检测--笔记

Comparison of advantages and disadvantages between most complete SQL and NoSQL

PAT甲级 1027 Colors in Mars

Partage de l'expérience du projet: mise en œuvre d'un pass optimisé pour la fusion IR de la couche mindstore

Technical dry goods | alphafold/ rosettafold open source reproduction (2) - alphafold process analysis and training Construction

VMware network mode - bridge, host only, NAT network

Leetcode 213: looting II

Technical dry goods Shengsi mindspire elementary course online: from basic concepts to practical operation, 1 hour to start!
![[coppeliasim4.3] C calls UR5 in the remoteapi control scenario](/img/ca/2f72ea3590c358a6c9884aaa1a1c33.png)
[coppeliasim4.3] C calls UR5 in the remoteapi control scenario
随机推荐
Read config configuration file of vertx
PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef
Industrial resilience
技术干货|百行代码写BERT,昇思MindSpore能力大赏
Some experiences of Arduino soft serial port communication
Why is data service the direction of the next generation data center?
Dora (discover offer request recognition) process of obtaining IP address
What did the DFS phase do
项目经验分享:基于昇思MindSpore,使用DFCNN和CTC损失函数的声学模型实现
最全SQL与NoSQL优缺点对比
技术干货 | AlphaFold/ RoseTTAFold开源复现(2)—AlphaFold流程分析和训练构建
Es writing fragment process
IPv4 address
Chapter VI - Containers
Inverted chain disk storage in Lucene (pfordelta)
Take you through the whole process and comprehensively understand the software accidents that belong to testing
Reconnaissance et détection d'images - Notes
[coppeliasim4.3] C calls UR5 in the remoteapi control scenario
Beginners use Minio
Project experience sharing: realize an IR Fusion optimization pass of Shengsi mindspire layer