go 错误处理panic recover

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

内容简介:当程序遇到致命错误时,就是停止运行Go 通过

当程序遇到致命错误时,就是停止运行

Go 通过 panic 函数来报告致命错误

func testError1()  {
    panic(errors.New("this is a error"))
}

go 错误处理panic recover

代码执行中出现错误

比如数组越界

index := 4
    arr := []int{1,2,3}
    _  = arr[index]

go 错误处理panic recover

那如何“拦截”运行时发生的错误?

recover函数

会返回一个interface{} 类型的结果,如果程序发生错误,就会返回非nil

和defer函数结合使用,就会将错误捕捉到进行处理

func testError()  {
    defer func() {
        if e := recover(); e != nil {
            fmt.Printf("panic : %s\n", e)
        }
    }()
    index := 4
    arr := []int{1,2,3}
    _  = arr[index]
}

go 错误处理panic recover


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

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

Modeling the Internet and the Web

Modeling the Internet and the Web

Pierre Baldi、Paolo Frasconi、Padhraic Smyth / Wiley / 2003-7-7 / USD 115.00

Modeling the Internet and the Web covers the most important aspects of modeling the Web using a modern mathematical and probabilistic treatment. It focuses on the information and application layers, a......一起来看看 《Modeling the Internet and the Web》 这本书的介绍吧!

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

在线压缩/解压 JS 代码

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

正则表达式在线测试

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

RGB CMYK 互转工具