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之后的逻辑不再执行

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

查看所有标签

猜你喜欢:

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

大数据

大数据

涂子沛 / 广西师范大学出版社 / 2013-4-1 / 49.90元

公布官员财产美国是怎么做的,美国能让少部人腐败起来吗,美国式上访是怎么回事,凭什么美国矿难那么少,全民医改美国做得到吗,美国总统大选有什么利器才能赢,下一轮全球洗牌我们世界工厂会被淘汰吗…… 除了上帝,任何人都必须用数据来说话。 大数据浪潮,汹涌来袭,与互联网的发明一样,这绝不仅仅是信息技术领域的革命,更是在全球范围启动透明政府、加速企业创新、引领社会变革的利器。现代管理学之父德鲁克有......一起来看看 《大数据》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具