2

【笔记】Go语言的错误处理机制

 1 year ago
source link: https://loli.fj.cn/2023/05/17/Go%E8%AF%AD%E8%A8%80%E7%9A%84%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86%E6%9C%BA%E5%88%B6/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【笔记】Go语言的错误处理机制

Go语言的错误处理机制学习笔记

  • 通过recover()函数可以捕获到错误
// 可能会panic的函数
func 函数名() {
// 延迟处理异常
defer func() {
if err := recover(); err != nil {
// 捕获到了异常
fmt.Println(err.Error())
}
}()

// 其他代码
...

}

自定义错误

创建一个自定义错误

err := errors.New("报错内容")

通过panic()函数输出错误信息并终止程序运行

if err != nil {
panic(err)
}

哔哩哔哩——尚硅谷


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK