Go错误处理(二)

1,.error接口的定义
  1. type error interface{
  2. Error()string
  3. }
2.error的使用
  1. func Foo(param int)(n int,err error){
  2. //函数定义
  3. }
  4. n,err:=Foo(0)
  5. if err!=nil{
  6. //错误处理
  7. }else{
  8. //使用返回值n
  9. }
3.自定义error类型
  •     定义一个承载错误信息的struct
  1. type PathErrorstruct{
  2. op string
  3. path string
  4. Err error
  5. }
  •    定义Error方法
  1. func (e *PathError)Error()string{
  2.     return e.op+" "+e.path+":"+e.Err.Error()
  3. }
defer:相当于C#中的Filnaly,总会被执行,并且他的执行顺序呢是先进后出
  1. func CopyFile(dst, src string){
  2. defer fmt.Println(dst)
  3. defer fmt.Println(src)
  4. fmt.Println("copy")
  5. }

copy

c:2.txt

c:oem8.txt

panic:相当于throw,recover:相当于catch

  1. defer func(){//必须要先声明defer,否则不能捕获到panic异常
  2. if err := recover(); err !=nil{
  3. fmt.Println(err)//这里的err其实就是panic传入的内容,55
  4. }
  5. }()
  6. f()
  7. func f(){
  8. fmt.Println("a")
  9. panic(55)
  10. fmt.Println("b")
  11. }
输出为

a

55

这里panic后面的fmt.Println("b")未被执行,所以后面的信息没有b

 



原文地址:https://www.cnblogs.com/anbylau2130/p/4240851.html