1. 程式人生 > 實用技巧 >Go語言錯誤處理

Go語言錯誤處理

go語言中使用error介面處理異常,兩個內建函式panic()和recover()以報告和處理執行時錯誤和程式中的錯

誤場景,一個defer關鍵字來處理順序執行。

一、error異常處理

01、error介面

go語言使用介面error處理異常。

type error interface { 
 Error() string
}

該介面處於errors包下,只有以下內容:

package errors
func New(text string) error { return &errorString{text} }
type errorString struct { text string }
func (e *errorString) Error() string { return e.text }

02、New()函式

可以直接使用New函式定義一個錯誤資料:

func main() {
	i,err:=walk(5)
	if err==nil{
		fmt.Println(i)
	}

	l,err:=walk(10)
	if err==nil{
		fmt.Println(l)
	}
	fmt.Println(err)
}

func walk(i int)(s string,err error){
	if i<10{
		return "ok",nil
	}
	return "no",errors.New("this is false")
}


//ok
//this is false

03、fmt.Errorf()函式

呼叫 errors.New 函式是非常稀少的,因為有一個方便的封裝函式 fmt.Errorf,它還會處理字串格式化。

package fmt
import "errors"
func Errorf(format string, args ...interface{}) error {
    return errors.New(Sprintf(format, args...))
}

如下:

func main() {
	errs:=run("hello")
	if errs!=nil{
		fmt.Println(errs)
	}
}

func run(s string)error{
	if len(s)<8{
		return fmt.Errorf("錯誤,%v資料長度過短",s)
	}
	fmt.Println("ok")
	return  nil
}

//錯誤,hello資料長度過短

二、defer關鍵字

defer 關鍵字將語句延遲執行,在defer所在的函式即將返回或者說結束時,將defer語句執行。

如果有多個被defer修飾的語句,那麼以棧(後進先出)的方式執行,即逆序執行。

func main()  {
	//defer關鍵字用於延遲執行
	fmt.Println("Start do ..")
	defer hello(1)
	defer hello(2)
	defer hello(3)
	fmt.Println("End do..")

}

func hello(i int){
	fmt.Println("Hello",i)

	defer ok(7)//在函式結束前執行
	fmt.Printf("hello%d函式結束啦\n",i)
	return
}

func ok(i int)  {
	fmt.Println("yes",i)
}

主函式執行完畢即將結束時,hello()函式從hello(3)開始執行,在hello(3)即將結束時執行ok(7),然後hello(2),hello(1)按照順序逆序執行。

Start do ..
End do..
Hello 3
hello3函式結束啦
yes 7
Hello 2
hello2函式結束啦
yes 7
Hello 1
hello1函式結束啦
yes 7

三、panic()、recover()函式

Go語言引入了兩個內建函式panic()和recover()以報告和處理執行時錯誤和程式中的錯 誤場景:

func panic(interface{})

func recover() interface{}

01、panic()

當在一個函式執行過程中呼叫panic()函式時,正常的函式執行流程將立即終止,但函式中 之前使用defer關鍵字延遲執行的語句將正常展開執行,錯誤資訊將被報 告,包括在呼叫panic()函式時傳入的引數,這個過程稱為錯誤處理流程。

func main() {

	defer fmt.Println("宕機也要執行的語句")
	defer fmt.Println("宕機之前的defer語句仍然執行")


	panic("錯誤,宕機")
	defer fmt.Println("宕機之前的語句不再執行")
	fmt.Println("no........")
}

宕機之前的defer語句仍然執行
宕機也要執行的語句
panic: 錯誤,宕機

goroutine 1 [running]:
main.main()
	E:/GoProject/aone/src/panicdemo.go:10 +0x147

Process finished with exit code 2

02、recover()

recover()函式用於終止錯誤處理流程。一般情況下,recover()應該在一個使用defer

關鍵字的函式中執行以有效擷取錯誤處理流程。

func main() {

	defer func() {
		err:=recover()
		fmt.Println("捕獲資料:",err)
	}()
	defer fmt.Println("宕機也要執行的語句")
	defer fmt.Println("宕機之前的defer語句仍然執行")


	panic("錯誤,宕機")
	fmt.Println("no........")

}

宕機之前的defer語句仍然執行
宕機也要執行的語句
捕獲資料: 錯誤,宕機