抛出 error 异常的方式

抛出 error 异常的方式

  • 一种方式是通过 error.New 产生异常。
func Sqrt(f float64) (float64, error) {
    if f < 0 {
        return 0, errors.New("math: square root of negative number")
    }
    // implementation
}
  • 另一种是通过 fmt.Errorf 产生
if f < 0 {
    return 0, fmt.Errorf("math: square root of negative number %g", f)
}

猜你喜欢

转载自blog.csdn.net/robin912/article/details/80753679