This is a creation in Article, where the information may have evolved or changed.
Golang has 2 built-in functions panic () and recover () to report and capture program errors that occur at run time , unlike error, where Panic-recover is typically used inside a function. Be careful not to misuse panic-recover, which can cause performance problems, which I generally use only when unknown input and unreliable requests.
Golang error Handling process: When a function has an exception or encounters panic () during execution, the normal statement terminates immediately, executes the defer statement, reports the exception information, and exits Goroutine. If the recover () function is used in defer, an error message is captured that causes the error message to terminate the report.
Example:
Copy CodeThe code is as follows: Package main
Import (
"Log"
"StrConv"
)
Capturing program exceptions caused by 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 issues
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
It is hoped that this article will be helpful to everyone's go language programming.