Golang exception handling mechanism Panic-defer-recover

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

What is the mechanism used for exception processing in go?

A sentence summary:

You can throw an panic exception in go and then catch the exception through recover in defer and then handle it normally.

package mainimport "fmt"func main() {    defer func() { // 必须要先声明defer,否则不能捕获到panic异常        fmt.Println("1")        if err := recover(); err != nil {            fmt.Println(err) // 这里的err其实就是panic传入的内容,the program is crashed        }        fmt.Println("2")    }()    ftest()    f()}func f() {    fmt.Println("b")    panic("the program is crashed")    fmt.Println("c")}func ftest() {    defer fmt.Println("AA")    defer fmt.Println("BB")    fmt.Println("CC")    return    fmt.Println("DD")}

You may be the first time I have the following questions in my mind:

    • when does Q1:defer execute?
    • Q2: In What order are multiple defer keywords in the program executed?
    • After the Q3:recover recovery, will the program * return to the place where the exception occurred and continue to run downwards?

Shall we answer one by one according to the result of execution?

CCBBAAb1the program is crashed2

A1: CC After printing the program return, and then printing BB , indicating that the function returned before the execution of the defer statement, do not print DD , stating that defer must be written before the program return before the Add execution before returning
A2: Print BB after printing AA , stating that defer execution order is declared after the first execution
A3: The program does not print c , stating that the program after recover recovery * will not return to the place where the exception occurred continue to run downwards

Reference:
Http://www.cnblogs.com/ghj1976/archive/2013/02/11/2910114.html

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.