Go language exception Handling Defer\panic\recover

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The go language pursues simplicity and elegance, so the go language does not support the exception of traditional try...catch...finally, because the designers of the go language think that mixing exceptions with control structures can easily confuse the code. Because developers are prone to abuse exceptions, even a small error throws an exception. In the Go language, return errors using multivalued returns. Do not use exceptions to replace errors, not to control processes. In very rare cases, that is, when a real exception is encountered (such as a divisor of 0). Before using the exception process introduced in go: defer, panic, recover.

These unusual usage scenarios can be described as simple: go can throw a panic exception, then catch the exception in defer with recover and then handle it normally.

Example code:

Package Main Import"FMT"Func Main () {defer func () {//You must declare defer first, or you cannot catch a panic exceptionFMT. Println ("C")        ifErr:=recover (); err!=nil{FMT. PRINTLN (ERR)//The err here is actually the panic incoming content,} fmt. Println ("D")} () () f ()} func f () {fmt. Println ("a") Panic ( -) fmt. Println ("b") fmt. Println ("F")} output result: AC -Dexit Code0, process exited normally.

Reference: http://blog.csdn.net/ghost911_slb/article/details/7831574

Defer

Defer English original meaning: VI. Defer, postpone, obey Vt. Make a postponement of; postpone.

Defer's ideas are similar to destructors in C + +, but the "destructor" in the Go language is not an object, but a function, and defer is the statement to be executed at the end of a function. Note that the emphasis here is on adding, not specifying, since destructors in C + + are static, and defer in Go is dynamic.

int {  defer func () {    result+ +  } ()  return0}

The above function returns 0 because the function has not yet been added to the defer.

It is also worth mentioning that defer can be multiple times to form a defer stack, after which the defer statement is called first when the function returns.

Reference: http://weager.sinaapp.com/?p=31

Panic

Panic English original meaning: N. Panic, adj, panic, fear, no reason, Vt. Make Panic VI. Very alarmed.

The panic is used to indicate a very serious unrecoverable error. In the go language this is a built-in function that receives a value of type interface{} (that is, any value) as a parameter. The panic function is like the anomaly of our usual contact. However, go is not try...catch, so panic generally causes the program to hang (unless recover). So, the exception in the go language, that's really abnormal. You can try, call panic to see, the program immediately hangs, and then the go Run will print out the call stack.
However, the key point is that even when the function is panic, the function does not go down, the runtime is not immediately upward transfer panic, but to defer that, and so defer things are running out, panic and then passed upward. So this time defer a bit like the finally in try-catch-finally.
Panic is so simple. Throws a true sense of exception.

Recover

Recover English Original: Vt. To recover from, to make up for or regain VI. To regain the ball N. Revert to a ready posture

As mentioned above, panic's function does not return immediately, but defer first and then returns. At this time (defer), if there is a way to capture panic, and prevent panic transmission, then the exception of the processing mechanism is perfect.

The go language provides the recover built-in function, mentioned earlier, once panic, logic will go to defer that, then we wait in the defer, the call recover function will capture the current panic (if any), the captured panic will not be passed up, Thus, the world resumed peace. You can do what you want to do.

However, it is important to note that after recover, the logic does not revert to the panic point, and the function will return after the defer.

There is an example of using go to implement exception handling like Try catch in:

http://www.douban.com/note/238705941/

Conclusion:

Go does not completely negate the existence of exceptions, and strongly discourages the use of multiple exceptions.

Reference: http://blog.dccmx.com/2012/01/exception-the-go-way/

http://kejibo.com/golang-exceptions-handle-defer-try/

http://bookjovi.iteye.com/blog/1335282

Https://github.com/astaxie/build-web-application-with-golang/blob/master/02.3.md

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.