golang错误处理之panic和recover

前端之家收集整理的这篇文章主要介绍了golang错误处理之panic和recover前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

panic()类似c++中的throw

recover()类似c++中的catch


func CopyFile(SrcFileName,DstFileName string) (w int64,err error) {
	defer func() {
		if r := recover(); r != nil {
			fmt.Printf("Runtime error is %v\n",r)
		}
	}()

	SFile,e := os.Open(SrcFileName)
	if e != nil {
		panic("the src file is not exist...")
		return
	}
	defer SFile.Close()

	DFile,e := os.Create(DstFileName)
	if e != nil {
		panic("the dst file is not exist...")
		return
	}
	defer DFile.Close()

	// anonymous function
	/*
		defer func() {
			SFile.Close()
			DFile.Close()
		}
	*/
	return io.Copy(DFile,SFile)
}
原文链接:https://www.f2er.com/go/190043.html

猜你在找的Go相关文章