This is a creation in Article, where the information may have evolved or changed.
What is the mechanism used for exception processing in go?
A sentence summary:
You can throw an panic exception in go and then catch the exception through recover in defer and then handle it normally.
package mainimport "fmt"func main() { defer func() { // 必须要先声明defer,否则不能捕获到panic异常 fmt.Println("1") if err := recover(); err != nil { fmt.Println(err) // 这里的err其实就是panic传入的内容,the program is crashed } fmt.Println("2") }() ftest() f()}func f() { fmt.Println("b") panic("the program is crashed") fmt.Println("c")}func ftest() { defer fmt.Println("AA") defer fmt.Println("BB") fmt.Println("CC") return fmt.Println("DD")}
You may be the first time I have the following questions in my mind:
- when does Q1:defer execute?
- Q2: In What order are multiple defer keywords in the program executed?
- After the Q3:recover recovery, will the program * return to the place where the exception occurred and continue to run downwards?
Shall we answer one by one according to the result of execution?
CCBBAAb1the program is crashed2
A1: CC
After printing the program return, and then printing BB
, indicating that the function returned before the execution of the defer statement, do not print DD
, stating that defer must be written before the program return before the Add execution before returning
A2: Print BB
after printing AA
, stating that defer execution order is declared after the first execution
A3: The program does not print c
, stating that the program after recover recovery * will not return to the place where the exception occurred continue to run downwards
Reference:
Http://www.cnblogs.com/ghj1976/archive/2013/02/11/2910114.html