5.7 Go catch the exception

5.7 Go catch the exception

Go abnormal language processing is different from other languages ​​to handle exceptions.

传统语言处理异常:
try 
catch
finally

go Language

引入了defer、panic、recover
1.Go程序抛出一个panic异常,在defer中通过recover捕获异常,然后处理

2. defer recover and catch exceptions

package main

import "fmt"

func test() {
    //在函数退出前,执行defer
    //捕捉异常后,程序不会异常退出
    defer func() {
        err := recover() //内置函数,可以捕捉到函数异常
        if err != nil {
            //这里是打印错误,还可以进行报警处理,例如微信,邮箱通知
            fmt.Println("err错误信息:", err)
        }
    }()

    //如果没有异常捕获,直接报错panic,运行时出错
    num1 := 10
    num2 := 0
    res := num1 / num2
    fmt.Println("res结果:", res)

}

func main() {
    test()
    fmt.Println("如果程序没退出,就走我这里")
}

Use recover the captured exception goroutine

在goroutine中如果出现了panic,整个程序也会崩溃,因此在goroutine中进行异常捕获,保障程序正常运转。

Sample Code

package main

import (
    "fmt"
    "time"
)

func test() {
    for i := 0; i < 10; i++ {
        time.Sleep(time.Second)
        fmt.Println("你好,大妹子,我是你表哥")
    }
}

func test2() {
    //测试一个异常goroutine
    //使用defer+recover捕获异常
    defer func() {
        //匿名函数来捕获异常
        if err := recover(); err != nil {
            fmt.Println("test2函数出错,", err)
        }
    }()

    //主动模拟异常,对一个未初始化的map赋值,引出panic异常
    var myMap map[int]string
    myMap[0] = "你妹呀"
}

func main() {
    go test()
    go test2()

    time.Sleep(time.Second * 10)
}

2.1.1. Errors package

package main

import (
    "errors"
    "fmt"
)

func checkAge(age int) error {
    if age < 0 {
        err := fmt.Errorf("输入年龄不合法")
        return err
    }
    fmt.Println("年龄是:", age)
    //正常error类型返回nil,代表无错
    return nil
}

func main() {
    //New函数,返回一个结构体对象
    err1 := errors.New("自定义的错误信息,你看我好玩吗")
    fmt.Println(err1.Error()) //调用Error方法
    fmt.Printf("%T\n", err1)  //结构体指针对象

    //创建error另一个方法,其实也是通过erros.New()创建的
    err2 := fmt.Errorf("自定义错误状态码:%d", 500)
    fmt.Printf("%T\n", err2) //结构体指针对象
    fmt.Println(err2.Error())

    //测试error
    err3:=checkAge(-1)
    if err3!=nil{
        fmt.Println(err3.Error())
        return
    }
    fmt.Println("程序正常运行")
}

Guess you like

Origin www.cnblogs.com/open-yang/p/11256858.html