[golang] 錯誤處理

[golang] 錯誤處理

Go語言的錯誤處理方式

Go語言 提供了兩種錯誤處理方式:golang

  • 返回錯誤模式: 函數的返回是一個複合類型,其中一個類型(習慣上是最後一個類型)是 error ,相似於:(, error)

這種模式被指望處理的場景是:當錯誤發生的狀況下,在處理錯誤後,程序扔能夠繼續執行下去。函數

  • 中斷/恢復模式:panic/recover

中斷/恢復模式適用於:當錯誤發生的狀況下,處理錯誤後,程序沒法繼續執行下去,須要中斷當前的程序或者協程。code

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語言中, 當一個錯誤發生時,但願處理這個錯誤,而後繼續執行。所以默認的錯誤處理模式是返回包含錯誤變量的複合結果。ci

func returnError() (ret interface{}, err error) {
	return nil, &PathError{Op: "open", Path: "/root"}
}


func main() {
	_, err := returnError()
	if err != nil {
		...
	}

}

panic 和 recover

當錯誤發生時,程序沒法執行下去的時候,這時指望終止程序或者終止當前的協程,在這種狀況下,Go語言提供了內嵌函數 panicstring

panic 函數的參數能夠是任何類型,通常會使用 stringit

recover 用於在上層抓住 panic 中的參數,並作適當的處理。io

有趣的是,panic()/recover()有點兒像是 try/catchclass

示例:

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"}
}
相關文章
相關標籤/搜索