当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > GO基础之异常处理

GO基础之异常处理

2019年11月08日  | 移动技术网IT编程  | 我要评论

一、异常

1、 错误指程序中出现不正常的情况,从而导致程序无法正常执行。
•大多语言中使用try... catch... finally语句执行。
假设我们正在尝试打开一个文件,文件系统中不存在这个文件。这是一个异常情况,它表示为一个错误。
2、 go语言中没有try...catch

  • • go语言通过内置的错误类型提供了非常简单的错误处理机制。
  • •错误值可以存储在变量中,通过函数中返回。
  • 如果一个函数或方法返回一个错误,按照惯例,它必须是函数返回的最后一个值。
  • •处理错误的惯用方式是将返回的错误与nil进行比较。
  • nil值表示没有发生错误,而非nil值表示出现错误。
  • •如果不是nil,需打印输出错误。

go中error的源码

package errors

// new returns an error that formats as the given text.
// each call to new returns a distinct error value even if the text is identical.
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
}

 

二、go中的异常处理

 

 

 

package main

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

func main() {
    //    异常情况1
    res := math.sqrt(-100)
    fmt.println(res)

    res , err := sqrt(-100)
    if err != nil {
        fmt.println(err)
    } else {
        fmt.println(res)
    }


    //异常情况2
    //res = 100 / 0
    //fmt.println(res)
    res , err = divide(100 , 0)
    if err != nil {
        fmt.println(err.error())
    } else {
        fmt.println(res)
    }

    //异常情况3
    f, err := os.open("/abc.txt")
    if err != nil {
        fmt.println(err)
    } else {
        fmt.println(f.name() , "该文件成功被打开!")
    }

}

//定义平方根运算函数
func sqrt(f float64)(float64 , error) {
    if f<0 {
        return 0 , errors.new("负数不可以获取平方根")
    } else {
        return math.sqrt(f) , nil
    }
}

//定义除法运算函数
func divide(dividee float64 , divider float64)(float64 , error) {
    if divider == 0 {
        return 0 , errors.new("出错:除数不可以为0!")
    } else {
        return dividee / divider , nil
    }
}

go中error的创建方式

//error创建方式一
func sqrt(f float64)(float64 , error) {
    if f<0 {
        return 0 , errors.new("负数不可以获取平方根")
    } else {
        return math.sqrt(f) , nil
    }
}
//error创建方式二;设计一个函数:验证年龄。如果是负数,则返回error
func checkage(age int) (string, error) {
    if age < 0 {
        err := fmt.errorf("您的年龄输入是:%d , 该数值为负数,有错误!", age)
        return "", err
    } else {
        return fmt.sprintf("您的年龄输入是:%d ", age), nil
    }
}

四、自定义错误

• 1、定义一个结构体,表示自定义错误的类型
• 2、让自定义错误类型实现error接口的方法:error() string
• 3、定义一个返回error的函数。根据程序实际功能而定。

package main

import (
    "time"
    "fmt"
)

//1、定义结构体,表示自定义错误的类型
type myerror struct {
    when time.time
    what string
}

//2、实现error()方法
func (e myerror) error() string {
    return fmt.sprintf("%v : %v", e.when, e.what)
}

//3、定义函数,返回error对象。该函数求矩形面积
func getarea(width, length float64) (float64, error) {
    errorinfo := ""
    if width < 0 && length < 0 {
        errorinfo = fmt.sprintf("长度:%v, 宽度:%v , 均为负数", length, width)
    } else if length < 0 {
        errorinfo = fmt.sprintf("长度:%v, 出现负数 ", length)
    } else if width < 0 {
        errorinfo = fmt.sprintf("宽度:%v , 出现负数", width)
    }
    if errorinfo != "" {
        return 0, myerror{time.now(), errorinfo}
    } else {
        return width * length, nil
    }
}

func main() {
    res , err := getarea(-4, -5)
    if err != nil {
        fmt.printf(err.error())
    } else {
        fmt.println("面积为:" , res)
    }
}

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网