This is a creation in Article, where the information may have evolved or changed. Everyone knows that the panic in Golang is equivalent to the throw in other languages, and recover is equivalent to the CACTH in other languages, but Golang's recover mechanism requires the defer function to execute catchpanic
Probably mean the following
Func Protect (G func ()) { Defer func () { Log. Println ("Done") PRINTLN executes normally even if there is a panic If x: = Recover (); X! = Nil { Log. Printf ("Run Timepanic:%v", X) } }() Log. Println ("Start") g ()}
This seems to be no different from try catch, but it is different if we want to implement the following functions in a different language.
int Test () { try { DoSomething (); } catch { Return 1 } Return 2}
It is obvious that this function needs to be able to return different values depending on whether or not an exception occurred.
In fact, this problem with recover and panic does not matter, the problem is purely defer problem, that is, can not be in the defer function to modify the current function of the return value, the answer is of course yes, you just need to name the return value on the line
Func routine () (b bool) { Defer func () { ERR: = Recover () If err! = Nil { Fmt. Printf ("errfound\n") B = True } }() If Rand. Int () = = 1 { Panic ("Hello") } B = False Return
But if you think about it in the deep, you will feel that this realization is also quite a pit dad, for example, there are two panic in the time, how to do? Of course there is a way, but it is more ugly, here is not an example of the clear.
This article is from the Linux commune website (www.linuxidc.com) Original link: http://www.linuxidc.com/Linux/2013-04/83105.htm
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