This article analyzes the go language exception handling mechanism panic and recover. Share to everyone for your reference. Specifically as follows:
Golang has 2 built-in functions panic () and recover () to report and capture Run-time error, unlike error, Panic-recover is commonly used within functions. It is important to be careful not to misuse panic-recover, which can cause performance problems that I normally use only when unknown inputs and unreliable requests.
Golang error Handling process: When a function in the execution of the exception or encountered panic (), the normal statement will terminate immediately, and then execute the defer statement, then report the exception information, and finally exit Goroutine. If the recover () function is used in defer, the error message is captured, causing the error message to terminate the report.
Example:
Copy Code code as follows:
Package Main
Import (
"Log"
"StrConv"
)
Catch a program exception caused by an unknown input
Func catch (nums. int) int {
Defer func () {
If r: = Recover (); R!= Nil {
Log. Println ("[E]", R)
}
}()
return nums[1] * nums[2] * nums[3]//index out of range
}
Unsolicited panic, deprecated, may cause performance problems
Func toFloat64 (num string) (float64, error) {
Defer func () {
If r: = Recover (); R!= Nil {
Log. Println ("[W]", R)
}
}()
If num = "" {
Panic ("param is null")//Active Throw Panic
}
Return StrConv. parsefloat (num, 10)
}
Func Main () {
catch (2, 8)
ToFloat64 ("")
}
The output is as follows:
2014/11/01 22:54:23 [E] Runtime error:index out of range
2014/11/01 22:54:23 [W] param is null
I hope this article will help you with your go language program.