go recover

recover是Go语言的内建函数,它用于从panic中恢复,阻止panic继续传播,并返回触发panic的值。如果在非延迟函数或者没有发生panic的情况下调用recover,它将不会有任何效果,即返回nil。
通常,recover需要与defer和panic一起使用。当panic被触发后,defer会保证recover总是被最后调用。如果recover成功地恢复了panic,程序会从触发panic的函数中返回,继续执行其他代码。

package main

import "fmt"

func f() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("Recovered in f", r)
		}
	}()
	fmt.Println("Calling g.")
	g(0)
	fmt.Println("Returned normally from g.")
}

func g(i int) {
	if i > 3 {
		fmt.Println("Panicking!")
		panic(fmt.Sprintf("%v", i))
	}
	defer fmt.Println("Defer in g", i)
	fmt.Println("Printing in g", i)
	g(i + 1)
}

func main() {
	f()
}

输出:
Calling g.
Printing in g 0
Printing in g 1
Printing in g 2
Printing in g 3
Panicking!
Defer in g 3
Defer in g 2
Defer in g 1
Defer in g 0
Recovered in f 4

你可能感兴趣的:(Go,Go,后端)