Go language exception handling mechanism panic and recover analysis _golang

Source: Internet
Author: User
Tags error handling exception handling

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.

Related Article

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.