一、例外
1、 錯誤指程式中出現不正常的情況,從而導致程式無法正常執行,
•大多語言中使用try... catch... finally陳述句執行,
假設我們正在嘗試打開一個檔案,檔案系統中不存在這個檔案,這是一個例外情況,它表示為一個錯誤,
2、 Go語言中沒有try...catch
- • Go語言通過內置的錯誤型別提供了非常簡單的錯誤處理機制,
- •錯誤值可以存盤在變數中,通過函式中回傳,
- 如果一個函式或方法回傳一個錯誤,按照慣例,它必須是函式回傳的最后一個值,
- •處理錯誤的慣用方式是將回傳的錯誤與nil進行比較,
- nil值表示沒有發生錯誤,而非nil值表示出現錯誤,
- •如果不是nil,需列印輸出錯誤,
go中error的原始碼
package errors// New returns an error that formats as the given text.// Each call to New returns a distinct error value even if the text is identical.func New(text string) error { return &errorString{text}}// errorString is a trivial implementation of error.type errorString struct { s string}func (e *errorString) Error() string { return e.s}
二、go中的例外處理


package mainimport ( "math" "fmt" "os" "github.com/pkg/errors")func main() { // 例外情況1 res := math.Sqrt(-100) fmt.Println(res) res , err := Sqrt(-100) if err != nil { fmt.Println(err) } else { fmt.Println(res) } //例外情況2 //res = 100 / 0 //fmt.Println(res) res , err = Divide(100 , 0) if err != nil { fmt.Println(err.Error()) } else { fmt.Println(res) } //例外情況3 f, err := os.Open("/abc.txt") if err != nil { fmt.Println(err) } else { fmt.Println(f.Name() , "該檔案成功被打開!") }}//定義平方根運算函式func Sqrt(f float64)(float64 , error) { if f<0 { return 0 , errors.New("負數不可以獲取平方根") } else { return math.Sqrt(f) , nil }}//定義除法運算函式func Divide(dividee float64 , divider float64)(float64 , error) { if divider == 0 { return 0 , errors.New("出錯:除數不可以為0!") } else { return dividee / divider , nil }}View Code
go中error的創建方式
//error創建方式一func Sqrt(f float64)(float64 , error) { if f<0 { return 0 , errors.New("負數不可以獲取平方根") } else { return math.Sqrt(f) , nil }}//error創建方式二;設計一個函式:驗證年齡,如果是負數,則回傳errorfunc checkAge(age int) (string, error) { if age < 0 { err := fmt.Errorf("您的年齡輸入是:%d , 該數值為負數,有錯誤!", age) return "", err } else { return fmt.Sprintf("您的年齡輸入是:%d ", age), nil }}
四、自定義錯誤
• 1、定義一個結構體,表示自定義錯誤的型別
• 2、讓自定義錯誤型別實作error介面的方法:Error() string
• 3、定義一個回傳error的函式,根據程式實際功能而定,

package mainimport ( "time" "fmt")//1、定義結構體,表示自定義錯誤的型別type MyError struct { When time.Time What string}//2、實作Error()方法func (e MyError) Error() string { return fmt.Sprintf("%v : %v", e.When, e.What)}//3、定義函式,回傳error物件,該函式求矩形面積func getArea(width, length float64) (float64, error) { errorInfo := "" if width < 0 && length < 0 { errorInfo = fmt.Sprintf("長度:%v, 寬度:%v , 均為負數", length, width) } else if length < 0 { errorInfo = fmt.Sprintf("長度:%v, 出現負數 ", length) } else if width < 0 { errorInfo = fmt.Sprintf("寬度:%v , 出現負數", width) } if errorInfo != "" { return 0, MyError{time.Now(), errorInfo} } else { return width * length, nil }}func main() { res , err := getArea(-4, -5) if err != nil { fmt.Printf(err.Error()) } else { fmt.Println("面積為:" , res) }}View Code
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/67386.html
標籤:Go
上一篇:go-面向物件編程(上)

