什么是Error

2018-11-13  本文已影响0人  bocsoft
package main

import (
    "fmt"
    "github.com/pkg/errors"
    "os"
    "reflect"
)

func main() {
    f, err := os.Open("NoFileExists")
    fmt.Println(err)                 //open NoFileExists: The system cannot find the file specified.
    fmt.Println(f)                   //<nil>
    fmt.Println(reflect.TypeOf(err)) //*os.PathError
    fmt.Println(err.Error())         //open NoFileExists: The system cannot find the file specified.

    r, err1 := Num(1200).Divide(0)
    fmt.Println(r)                    //0
    fmt.Println(err1)                 //can not divide 0
    fmt.Println(reflect.TypeOf(err1)) //*errors.fundamental
    fmt.Println(err1.Error())         //can not divide 0.

    r1, err2 := Sqrt(-100)
    fmt.Println(err2)                 //root of negative number -100
    fmt.Println(r1)                   //0
    fmt.Println(reflect.TypeOf(err2)) //*errors.errorString

}

type Num int

func (n Num) Divide(x int) (r int, err error) {
    if x == 0 {
        return 0, errors.New("can not divide 0.")//新建一个Error
    }
    r = int(n) / x
    return r, nil
}

func Sqrt(n float64) (float64, error) {
    if n < 0 {
        return 0, fmt.Errorf("root of negative number %g", n) //格式化错误信息
    }
    return 100, nil
}



上一篇 下一篇

猜你喜欢

热点阅读