[Go] Defer, panic, recover

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
posted @ 2022-09-06 02:24  Zhentiw  阅读(21)  评论(0编辑  收藏  举报