Defer, with recover and anonymous function handlers, a critical error (panic statement), a program error, continues execution, similar to the Python language, the try...except
finally
statement.
//defer,recover机制,处理panic引发的机制package mainimport "fmt"func main() { A() B() C()}func A() { fmt.Println("func a")}func B() { defer func() { //defer函数放在panic之前 if err := recover(); err != nil { //注册recover函数(判断是否触发panic错误),并判断 fmt.Println("Recover in B") //如果程序出现panic,并且err不为nil(真实存在) } }() //记住,defer的匿名函数大括号后要加上() panic("Panic B") //跳过程序错误,继续后面的执行。}func C() { fmt.Println("func C")}/*输出A()--> func aB()--> Recover in BC()-->
~ ~ Leave a question, interested in a small partner welcome to answer
Run the following code and parse the output
package Mainimport "FMT" Func Main () {var fs = [4]func () {}//define a variable FS, type is an array, the type of the array element is funcfor I: = 0 ; I < 4; i++ {defer FMT. Println ("Defer i=", i) defer func () {fmt. PRINTLN ("Defer closure i=", I)} () Fs[i] = func () {fmt. Println ("Closure i=", i)}}for _, F: = Range fs {f ()}}