goang 错误&异常处理机制

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

内容简介: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之后的逻辑不再执行

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

查看所有标签

猜你喜欢:

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

Head First PHP & MySQL

Head First PHP & MySQL

Lynn Beighley、Michael Morrison / O'Reilly Media / 2008-12-29 / USD 44.99

If you're ready to create web pages more complex than those you can build with HTML and CSS, Head First PHP & MySQL is the ultimate learning guide to building dynamic, database-driven websites using P......一起来看看 《Head First PHP & MySQL》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

URL 编码/解码
URL 编码/解码

URL 编码/解码