First of all, I'm sorry, because of the move, too many recent things to deal with, resulting in more slow article updates.
In this article, we talk about exception handling in go.
Go provides two built-in functions panic () and recover () for exception handling.
Go, the overall principle of exception handling is: Multi-use errors package, less use of panic.
For predictable errors, such as network connection failures, errors is generally used, and only critical errors are used panic.
Remember a big rule: Panic will cause the program to hang directly unless the recover method is called.
Calling panic inside a function immediately terminates the execution of the current function, which is returned by the current call stack, up to the topmost main function or captured by a layer of recover.
See Example:
Package Main
Import (
"FMT"
)
Func Main () {
Fmt. PRINTLN ("Start main")
Sub ()
Fmt. PRINTLN ("End main")
}
Func Sub () {
Fmt. Println ("before Panic")
Panic ("Golang_everyday")
Fmt. Println ("after Panic")
}
Execution Result:
Start Main
Before panic
Panic:golang_everyday
Goroutine 1 [Running]:
Main.sub ()
/users/baiyuxiong/go/src/baiyuxiong.com/demo/panic.go:18 +0x124
Main.main ()
/users/baiyuxiong/go/src/baiyuxiong.com/demo/panic.go:10 +0XDF
Goroutine 2 [runnable]:
Runtime.forcegchelper ()
/usr/local/go/src/runtime/proc.go:90
Runtime.goexit ()
/usr/local/go/src/runtime/asm_amd64.s:2232 +0x1
Goroutine 3 [runnable]:
Runtime.bgsweep ()
/usr/local/go/src/runtime/mgc0.go:82
Runtime.goexit ()
/usr/local/go/src/runtime/asm_amd64.s:2232 +0x1
Goroutine 4 [runnable]:
Runtime.runfinq ()
/usr/local/go/src/runtime/malloc.go:712
Runtime.goexit ()
/usr/local/go/src/runtime/asm_amd64.s:2232 +0x1
Exit Status 2
As you can see, after panic, the program stops executing, the layer exits to main, exits the entire program, and then prints the stack information.
If we are in the sub function, use defer for recover:
Package main Import ("FMT") Func main () {FMT. Println ("Start Main") Sub () Fmt. Println ("End Main")} func sub () {Defer handler () FMT. Println ("before Panic") Panic ("Golang_everyday") fmt. Println ("After panic")} func handler () {ifERR: = Recover (); Err! =Nil {fmt. Println ("Recover msg:", Err)} Else{fmt. Println ("Recover OK")}}
Execution Result:
Start Main
Before panic
Recover Msg:golang_everyday
End Main
As you can see, the sub function is not finished, and panic executes the defer to return to the upper-level main function, but the main function execution is finished.
This is because recover prevents the continuation of the exception from propagating. He confined the panic to a certain extent.
It was like a bomb was lost in the house (panic produced), everyone would have to hang up (panic passed to main, the whole program quit), but there is a young man named recover very brave, duang!!! Hug to the bomb up, the loss of control in a certain range, if the young man the sooner the bomb, the less injured people.
Go exception handling