Go編程提供了一個(gè)非常簡(jiǎn)單的錯(cuò)誤處理框架,以及內(nèi)置的錯(cuò)誤接口類型,如下聲明:
type error interface {
Error() string
}
函數(shù)通常返回錯(cuò)誤作為最后一個(gè)返回值。 可使用errors.New來(lái)構(gòu)造一個(gè)基本的錯(cuò)誤消息,如下所示:
func Sqrt(value float64)(float64, error) {
if(value < 0){
return 0, errors.New("Math: negative number passed to Sqrt")
}
return math.Sqrt(value)
}
使用返回值和錯(cuò)誤消息,如下所示 -
result, err:= Sqrt(-1)
if err != nil {
fmt.Println(err)
}
package main
import "errors"
import "fmt"
import "math"
func Sqrt(value float64)(float64, error) {
if(value < 0){
return 0, errors.New("Math: negative number passed to Sqrt")
}
return math.Sqrt(value), nil
}
func main() {
result, err:= Sqrt(-1)
if err != nil {
fmt.Println(err)
}else {
fmt.Println(result)
}
result, err = Sqrt(9)
if err != nil {
fmt.Println(err)
}else {
fmt.Println(result)
}
}
當(dāng)上述代碼編譯和執(zhí)行時(shí),它產(chǎn)生以下結(jié)果:
Math: negative number passed to Sqrt
3