当前位置:网站首页>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()
}

边栏推荐
- IO stream system and FileReader, filewriter
- Traversal in Lucene
- Various postures of CS without online line
- Jeecg data button permission settings
- Summary of Arduino serial functions related to print read
- Technical dry goods Shengsi mindspire elementary course online: from basic concepts to practical operation, 1 hour to start!
- TreeMap
- Spa single page application
- JS monitors empty objects and empty references
- Es writing fragment process
猜你喜欢

Inverted chain disk storage in Lucene (pfordelta)

Project experience sharing: Based on mindspore, the acoustic model is realized by using dfcnn and CTC loss function

PAT甲级 1027 Colors in Mars

Robots protocol

项目经验分享:实现一个昇思MindSpore 图层 IR 融合优化 pass

TCP cumulative acknowledgement and window value update

技术干货|利用昇思MindSpore复现ICCV2021 Best Paper Swin Transformer

Lucene hnsw merge optimization

Technical dry goods Shengsi mindspire lite1.5 feature release, bringing a new end-to-end AI experience

昇思MindSpore再升级,深度科学计算的极致创新
随机推荐
Dora (discover offer request recognition) process of obtaining IP address
Introduction of buffer flow
Collector in ES (percentile / base)
密西根大学张阳教授受聘中国上海交通大学客座教授(图)
不出网上线CS的各种姿势
技术干货|AI框架动静态图统一的思考
【MySQL 12】MySQL 8.0.18 重新初始化
Topic | synchronous asynchronous
Comparison of advantages and disadvantages between most complete SQL and NoSQL
技术干货|昇思MindSpore初级课程上线:从基本概念到实操,1小时上手!
Understanding of class
Unified handling and interception of exception exceptions of vertx
Some basic operations of reflection
Realize the reuse of components with different routing parameters and monitor the changes of routing parameters
Technology dry goods | luxe model for the migration of mindspore NLP model -- reading comprehension task
Image recognition and detection -- Notes
Grpc message sending of vertx
Epoll related references
PgSQL converts string to double type (to_number())
Leetcode 213: looting II