goang 错误&异常处理机制

栏目: Go · 发布时间: 7年前

内容简介:golang 使用error接口作为标准错误接口,通常情况下错误处理方式error作为函数返回值时应该放在最后一个返回值:eg:

基本概念

  • 错误:意料之内,可能出的问题, 比如网络连接超时,json解析错误等
  • 异常:意料之外,不应该出的问题,比如空指针异常,下标溢出等异常

错误处理

golang 使用error接口作为标准错误接口,

通常情况下错误处理方式

if err != nil{
    //错误处理逻辑
}

error作为函数返回值时应该放在最后一个返回值:eg:

func get()(res string, err error){
    return
}

使用error作为返回值的规范是函数体内有可能产生多种错误时返回error,当仅有一种error的可能或者类型时应该用bool类型代替,这样更简洁,eg:

//此方法种只有一种逻辑上的错误,不应该返回error, 推荐使用checkNumAreaB函数的写法
func checkNumArea(num int) error {
    if num > 100{
        return errors.New("超出值域")
    }
    return nil
}

func checkNumAreaB(num int) bool {
    if num > 100{
        return false
    }
    return true
}

异常处理

The panic built-in function stops normal execution of the current goroutine. When a function F calls panic, normal execution of F stops immediately. Any functions whose execution was deferred by F are run in the usual way, and then F returns to its caller. To the caller G, the invocation of F then behaves like a call to panic, terminating G's execution and running any deferred functions. This continues until all functions in the executing goroutine have stopped, in reverse order. At that point, the program is terminated and the error condition is reported, including the value of the argument to panic. This termination sequence is called panicking and can be controlled by the built-in function recover.

从官方介绍可知panic调用会使整个调用栈逆序终止,最终导致整个程序终止并输出调中栈信息, 可使用recover方法捕获异常而避免程序终结,生产环境种必须有此操作以避免程序终止

panic类似 java 的throw python的raise, recover 类似try catch

常用处理方式如下

func A(){
    defer func(){
       fmt.Println("3") 
    }()
    defer func(){
        if err := recover(); err != nil{
            fmt.Println("err:", err)
        }
    }()
    
    panic("1")
    fmt.Println("2")
}
A()
//outout:
//err:1
//3
  • defer的执行逻辑时LIFO,
  • defer的执行是在函数执行完毕,return,panic之后的
  • panic之后的逻辑不再执行

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

绝对价值

绝对价值

[美] 伊塔马尔·西蒙森 艾曼纽·罗森 / 钱峰 / 中国友谊出版公司 / 2014-7 / 45.00元

绝对价值指的是经用户体验的产品质量,即使用某件产品或者享受某项服务的切实感受。 过去,消费就像是押宝。一件商品好不好,一家餐馆的环境如何,没有亲身体验过消费者无从得知,只能根据营销人员提供的有限信息去猜测。品牌、原产地、价位、广告,这些重要的质量线索左右着消费者的选择。 然而,互联网和新兴科技以一种前所未有的速度改变了商业环境。当消费者可以在购买前查看到交易记录和消费者评价,通过便捷的......一起来看看 《绝对价值》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具