Golang Panic Recover

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

Usage of exception handling painc () and recover () in the Go language

1. Painc usage is: used to throw an error. The Recover () usage is: Write Recover () in defer, and call this defer before the place where panic can occur (let the code execute when the System Method field ends.) When the program encounters a panic (of course, it can also call the normal exception), the system will skip the following code, enter defer, if the defer function recover (), then return the captured panic value.

2. Code:

 package main   import   "FMT"   func Main () {     fmt. Printf ( "Hello World My Name is%s, I ' m%d\r\n" ,  "Songxingzhu" ,  + )   & Nbsp; defer func () {          if  err: = Recover (); Err! = Nil {             fmt. Println ( "Out of the wrong:" , Err)         }    } ()     mypainc ()     fmt. Printf ( "should not be executed here!") )}func Mypainc () {      var  x =  (       var  y =  0      //panic ( "I was a big mistake!" )       var  c = x/y    fmt. Println (c)}  

 

3. Implementation results

Atom Runner: main.go

hello world my name is songxingzhu, I'm 26

出了错: runtime error: integer divide by zero

Exited with code=0 in 1.667 seconds

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.