[Go] Defer, panic, recover
Go defer recover panic
2023-09-14 08:59:12 时间
package main
import (
"fmt"
)
func recoverFromPanic() {
fmt.Println("defer")
}
func doThings() {
defer recoverFromPanic()
for i := 0; i < 5; i++ {
fmt.Println(i)
if i == 2 {
panic("NOT 2") // If there is a painc, it will find defer function run it
}
}
}
// Order:
// 0 1 2 defer panic: NOT 2
func main() {
doThings()
}
Notice the order of flow:
Print out:
0
1
2
defer
Panic: NOT 2
Which means defer run before panic
That's the chance we can do recover:
func recoverFromPanic() {
if r := recover(); r != nil {
fmt.Println("catch panic", r)
}
}
catch panic NOT 2
相关文章
- Go 缓冲信道
- [Go] 单元测试/性能测试 (go test)
- [Go] 开发 go web 项目,踩到的一些“坑”
- 【Go命令教程】3. go install
- 如何安装 第三方 Go 离线包? (GOPATH、 go install)
- Go语言的for循环
- 阿里 双11 同款流控降级组件 Sentinel Go 正式 GA,助力云原生服务稳稳稳
- 【Go语言】【4】GO语言类型和为类型增加方法
- go项目多阶段构建Dockerfile脚本示例
- 【GO】K8s 管理系统项目29[前端部分–Secret]
- 【Go基础】理解go语言类型
- 【Go应用】go实现rpc通信协议
- 【Go】go实现 — 链表
- Go语言精进自学系列 | 使用defer让函数更简洁、更健壮
- Go语言自学系列 | golang并发编程之原子变量的引入
- Go语言自学系列 | go语言中的流程控制
- Go语言自学系列 | golang中的if语句
- go语言笔记——go是有虚拟机runtime的,不然谁来做GC呢,总不会让用户自己来new和delete进行内存管理吧,还有反射!Go 的 runtime 嵌入到了每一个可执行文件当中
- go内建方法 new和make区别
- Go 每日一库之 cast
- 当 Go struct 遇上 Mutex
- Go实战--golang中defer的使用