Func Panic (interface{}) and Func recover () interface{} are the two functions used for error handling in Golang.
The function of panic is to throw an error message, and from its argument type it can be seen to throw any type of error message. When panic is called somewhere in the execution of the function, an error message is immediately thrown, and the normal execution of the function terminates, but the defer statement panic previously defined in the function is executed sequentially. The goroutine immediately stops executing.
Recover () is used to capture information from panic. Recover must be defined in the defer statement before panic. In this case, when panic is triggered, the goroutine will not simply terminate, but will execute the defer statement defined before it.
The following is a simple example:
--Capture your own set of panic errors:
Package Mainimport"FMT"Import"Math"func foo (aint) {defer FMT. Println ("Foo's out of here.") defer func () {ifr: = Recover (); r! =Nil {fmt. Printf ("error Caught:%s\n", R)} }() ifA <0{Panic ("You must enter a number greater than 0")} FMT. Println ("The square root of the number is:", Math. Sqrt (Float64 (a)))}func main () {varAinta=TenFMT. Printf ("a=%d\n", a) foo (a)varBintb= -TenFMT. Printf ("b=%d\n", B) foo (b) fmt. Println ("The Goroutine can also perform")}// ///////////A=TenThe square root of the number is:3.1622776601683795Foo quit, B.=-Tencaught error: Must enter a number greater than 0 foo exits the Goroutine can also perform process finished with exit code0
----
--Captures panic errors inside the Go language:
Package Mainimport"FMT"func foo () {defer func () {ifr: = Recover (); r! =Nil {fmt. Printf ("error Caught:%s\n", R)} }() varA, bintA, B=1,1C:=3/(A-b) fmt. Println (A, B, c)}func main () {foo ()}//====Caught error: Runtime Error:integer divide by zero