GO language exception handling

Learning a language, the first step in figuring out the logic judgment, the second step to thoroughly understand the logic error handling them.

go-language support multi-value return, we usually used to return a error. But only a simple function returns dependent and can not solve some of the false claims encountered in the work. We also need to rely on exception handling.

Exception handling go language of how to do it? With the following main functions.

  • panic()
  • recover()
package main

import "fmt"

func main() {
    test1()
    test2()
    test3()
}

func test1() {
    fmt.Println("i am test1")
}

func test2() {
    defer func() {
        if err := recover(); err != nil {
            fmt.Println("捕获异常", err) 
        }
    }()

    panic("have error !")

    fmt.Println("i am test2")
}

func test3() {
    fmt.Println("i am test3")
}

Output

i am test1
捕获异常 have error !
i am test3

We see, test2 function using the panic () throws an exception, this will interrupt the current code to run, to call a function defer, defer function using recover caught an exception, and processing is completed. Then the code will continue to walk test3 (), where you can simply understood as test2 own throw, catch and handle yourself, so if the exception that they can not handle it? Look at the following code.

package main

import "fmt"

func main() {
    defer func() {
        if err := recover(); err != nil {
            fmt.Println("捕获异常", err)
        }
    }()

    test1()
    test2()
    test3()
}

func test1() {
    fmt.Println("i am test1")
}

func test2() {
    panic("have error !")
    fmt.Println("i am test2")
}

func test3() {
    fmt.Println("i am test3")
}

Export

i am test1
捕获异常 have error !

When the code appears panic, error transfer layer by layer, similar to the exception is passed. defer until the first occurrence of the recover its capture

Reproduced in: https: //www.jianshu.com/p/3758978f8b1c

Guess you like

Origin blog.csdn.net/weixin_34040079/article/details/91180782
Recommended