• [golang] 错误处理


    [golang] 错误处理

    Go语言的错误处理方式

    Go语言 提供了两种错误处理方式:

    • 返回错误模式: 函数的返回是一个复合类型,其中一个类型(习惯上是最后一个类型)是 error ,类似于:(, error)

    这种模式被期望处理的场景是:当错误发生的情况下,在处理错误后,程序扔可以继续执行下去。

    • 中断/恢复模式:panic/recover

    中断/恢复模式适用于:当错误发生的情况下,处理错误后,程序无法继续执行下去,需要中断当前的程序或者协程。

    error 接口

    Go语言提供了内嵌接口 error,其定义是:

    type error interface {
        Error() string
    }
    

    因此,任何有 Error() string 方法的类型都可以被认为是Error类。

    type PathError struct {
    	Op   string // "open", "unlink", etc.
    	Path string // The associated file.
    }
    
    func (e *PathError) Error() string {
    	return e.Op + " " + e.Path
    }
    

    error 返回/处理模式

    Go语言中, 当一个错误发生时,希望处理这个错误,然后继续执行。因此默认的错误处理模式是返回包含错误变量的复合结果。

    func returnError() (ret interface{}, err error) {
    	return nil, &PathError{Op: "open", Path: "/root"}
    }
    
    
    func main() {
    	_, err := returnError()
    	if err != nil {
    		...
    	}
    
    }
    

    panic 和 recover

    当错误发生时,程序无法执行下去的时候,这时期望终止程序或者终止当前的协程,在这种情况下,Go语言提供了内嵌函数 panic

    panic 函数的参数可以是任何类型,一般会使用 string

    recover 用于在上层抓住 panic 中的参数,并做适当的处理。

    有趣的是,panic()/recover()有点儿像是 try/catch

    示例:

    package main
    
    import "fmt"
    
    // PathError records an error and the operation and
    // file path that caused it.
    type PathError struct {
    	Op   string // "open", "unlink", etc.
    	Path string // The associated file.
    }
    
    func (e *PathError) Error() string {
    	return e.Op + " " + e.Path
    }
    
    func main() {
    	defer func() {
    		if e := recover(); e != nil {
    			fmt.Println(e)
    		}
    	}()
    	_, err := returnError()
    	if err != nil {
    		panic(err.Error())
    	}
    
    }
    
    func returnError() (ret interface{}, err error) {
    	return nil, &PathError{Op: "open", Path: "/root"}
    }
    
    
    非常感谢阅读!如有不足之处,请留下您的评价和问题。
    请“推荐”本文!
  • 相关阅读:
    如何实现序列化为json
    unity中camera摄像头控制详解
    eclipse配置c开发环境
    uml和模式01
    angular2开发01
    微信公众平台开发01
    最新无线网卡驱动安装
    交换ctrl和caps_loack的新方法
    web.xml文件详解
    设计模式中的里氏代换原则
  • 原文地址:https://www.cnblogs.com/steven-yang/p/14630539.html
Copyright © 2020-2023  润新知