go chapter 5

https://blog.csdn.net/tennysonsky/article/details/78946265

error(不中断)、panic(中断)、recover(拦截中断  类似于 catch)

errors.New("a normal err1")  不会中断执行

import (
    "errors"
    "fmt"
)

func main() {
    var err1 error = errors.New("a normal err1")
    fmt.Println(err1) //a normal err1
}

panic(" error messages here ")、

func TestA() {
    fmt.Println("func TestA()")
}

func TestB() {
    panic("func TestB(): panic")
}

func TestC() {
    fmt.Println("func TestC()")
}

func main() {
    TestA()
    TestB()//TestB()发生异常,中断程序
    TestC()
}

  

panic

func TestA() {
    fmt.Println("func TestA()")
}

func TestB() (err error) {
    defer func() { //在发生异常时,设置恢复
        if x := recover(); x != nil {
            //panic value被附加到错误信息中;
            //并用err变量接收错误信息,返回给调用者。
            err = fmt.Errorf("internal error: %v", x)
        }
    }()

    panic("func TestB(): panic")
}

func TestC() {
    fmt.Println("func TestC()")
}

func main() {
    TestA()
    err := TestB()
    fmt.Println(err)
    TestC()

    /*
        运行结果:
        func TestA()
        internal error: func TestB(): panic
        func TestC()
    */
}

  

原文地址:https://www.cnblogs.com/webglcn/p/9405186.html