一. 错误
// The error built-in interface type is the conventional interface for
// representing an error condition, with the nil value representing no error.
type error interface {
Error() string
}
- Go语言中错误都作为方法/函数的返回值,因为Go语言认为使用其他语言类似try...catch这种方式会影响到程序结构
- 在Go语言标准库的errors包中提供了error接口的实现结构体errorString,并重写了error接口的Error()方法.额外还提供了快速创建错误的函数
package errors
// New returns an error that formats as the given text.
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
}
- 如果错误信息由很多变量(小块)组成,可以借助
fmt.Errorf("verb",...)
完成错误信息格式化,因为底层还是errors.New()
// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
func Errorf(format string, a ...interface{}) error {
return errors.New(Sprintf(format, a...))
}
二.自定义错误
func demo(i, k int) (d int, e error) {
if k == 0 {
e = errors.New("初始不能为0")
d=0
return
}
d = i / k
return
}
func main() {
result,error:=demo(6,0)
fmt.Println(result,error)
}
func demo(i, k int) (d int, e error) {
if k == 0 {
e = fmt.Errorf("%s%d和%d", "除数不能是0,两个参数分别是:", i, k)
d = 0
return
}
d = i / k
return
}
func main() {
result, error := demo(6, 0)
fmt.Println(result, error)
}
三.Go语言中错误处理方式
func demo(i, k int) (d int, e error) {
if k == 0 {
e = fmt.Errorf("%s%d和%d", "除数不能是0,两个参数分别是:", i, k)
d = 0
return
}
d = i / k
return
}
func main() {
result, _ := demo(6, 0)
fmt.Println(result)
}
func demo(i, k int) (d int, e error) {
if k == 0 {
e = fmt.Errorf("%s%d和%d", "除数不能是0,两个参数分别是:", i, k)
d = 0
return
}
d = i / k
return
}
func main() {
result, error := demo(6, 0)
if error != nil {
fmt.Println("发生错误", error)
return
}
fmt.Println("程序执行成功,结果为:", result)
}