当前位置:网站首页>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()
}
边栏推荐
- TreeMap
- Traversal in Lucene
- IO stream system and FileReader, filewriter
- 昇思MindSpore再升级,深度科学计算的极致创新
- 【LeetCode】3. Merge Two Sorted Lists·合并两个有序链表
- Qtip2 solves the problem of too many texts
- Common architectures of IO streams
- Longest common prefix and
- [Development Notes] cloud app control on device based on smart cloud 4G adapter gc211
- 项目经验分享:实现一个昇思MindSpore 图层 IR 融合优化 pass
猜你喜欢
圖像識別與檢測--筆記
Arduino Serial系列函数 有关print read 的总结
Partage de l'expérience du projet: mise en œuvre d'un pass optimisé pour la fusion IR de la couche mindstore
技术干货|昇思MindSpore NLP模型迁移之Roberta ——情感分析任务
Topic | synchronous asynchronous
Usage of requests module
【LeetCode】3. Merge Two Sorted Lists·合并两个有序链表
技术干货|昇思MindSpore NLP模型迁移之LUKE模型——阅读理解任务
Lucene skip table
昇思MindSpore再升级,深度科学计算的极致创新
随机推荐
【MySQL 12】MySQL 8.0.18 重新初始化
Sent by mqtt client server of vertx
Leetcode 198: house raiding
What did the DFS phase do
TypeScript let与var的区别
VMWare网络模式-桥接,Host-Only,NAT网络
Industrial resilience
Unified handling and interception of exception exceptions of vertx
Epoll related references
Topic | synchronous asynchronous
Vertx multi vertical shared data
【MySQL 13】安装MySQL后第一次修改密码,可以可跳过MySQL密码验证进行登录
How long is the fastest time you can develop data API? One minute is enough for me
Lucene hnsw merge optimization
Technical dry goods Shengsi mindspire operator parallel + heterogeneous parallel, enabling 32 card training 242 billion parameter model
Grpc message sending of vertx
论文学习——鄱阳湖星子站水位时间序列相似度研究
List exercises after class
技术干货 | AlphaFold/ RoseTTAFold开源复现(2)—AlphaFold流程分析和训练构建
技术干货|昇思MindSpore NLP模型迁移之LUKE模型——阅读理解任务