Panic and recover analysis of Go language exception processing mechanism

Source: Internet
Author: User
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.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.