Panic and recover in Golang (Catch exception)

Source: Internet
Author: User

Func Panic (interface{}) and Func recover () interface{} are the two functions used for error handling in Golang.

The function of panic is to throw an error message, and from its argument type it can be seen to throw any type of error message. When panic is called somewhere in the execution of the function, an error message is immediately thrown, and the normal execution of the function terminates, but the defer statement panic previously defined in the function is executed sequentially. The goroutine immediately stops executing.

Recover () is used to capture information from panic. Recover must be defined in the defer statement before panic. In this case, when panic is triggered, the goroutine will not simply terminate, but will execute the defer statement defined before it.

The following is a simple example:

--Capture your own set of panic errors:

Package Mainimport"FMT"Import"Math"func foo (aint) {defer FMT. Println ("Foo's out of here.") defer func () {ifr: = Recover (); r! =Nil {fmt. Printf ("error Caught:%s\n", R)} }()    ifA <0{Panic ("You must enter a number greater than 0")} FMT. Println ("The square root of the number is:", Math. Sqrt (Float64 (a)))}func main () {varAinta=TenFMT. Printf ("a=%d\n", a) foo (a)varBintb= -TenFMT. Printf ("b=%d\n", B) foo (b) fmt. Println ("The Goroutine can also perform")}// ///////////A=TenThe square root of the number is:3.1622776601683795Foo quit, B.=-Tencaught error: Must enter a number greater than 0 foo exits the Goroutine can also perform process finished with exit code0

----

--Captures panic errors inside the Go language:

Package Mainimport"FMT"func foo () {defer func () {ifr: = Recover (); r! =Nil {fmt. Printf ("error Caught:%s\n", R)} }()    varA, bintA, B=1,1C:=3/(A-b) fmt. Println (A, B, c)}func main () {foo ()}//====Caught error: Runtime Error:integer divide by zero

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.