其他分享
首页 > 其他分享> > [Go] Defer, panic, recover

[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

标签:Defer,defer,fmt,func,Go,recover,panic,recoverFromPanic
来源: https://www.cnblogs.com/Answer1215/p/16660303.html