error
error 是go语言内置的错误接口
type error interface {
Error() string
}
//构造error对象
err := errors.New("this is an error")
err := fmt.Errorf("this is an error")
//自定义错误接口
type NotNature float64
func (err NotNature) Error() string{
return fmt.Sprintf("自然数为大于或等于0的数: %v", float64(err))
}
//调用自定义错误
func Nature(x float64) (float64,error) {
if x<0 {
return 0,NotNature(x)
} else {
return x,nil
}
}
func main() {
fmt.Println(Nature(1))
fmt.Println(Nature(-1))
}
panic
go 不使用 try catch 捕获处理异常,而是使用panic 和 recover
func main(){
panic(errors.New(" i am a error") //panic 后面的程序不会被执行
fmt.Println("我不会执行")
}
if err:=recover();err!=nil{
fmt.Println(err)
}