goang 错误&异常处理机制

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

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

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

查看所有标签

猜你喜欢:

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

Python科学计算(第2版)

Python科学计算(第2版)

张若愚 / 清华大学出版社 / 2016-4-29 / 118

本书介绍如何用 Python 开发科学计算的应用程序,除了介绍数值计算之外,还着重介绍了如何制作交互式二维、三维图像,如何设计精巧的程序界面,如何与 C 语言编写的高速计算程序结合,如何编写声音、图像处理算法等内容。本书采用 IPython notebook 编写,所有的程序均能在本书提供的运行环境中正常运行,书中所印刷的图表以及程序输出为均为自动运行的结果,保证了书中所有程序的正确性以及可读性。......一起来看看 《Python科学计算(第2版)》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具