异常处理

1 出现异常时可以用panic输出(这里的输出是把panic里的内存输出到日志上),为了不让程序终止可以用defer函数结合recover,这样程序不会因异常直接退出,recover可以把panic中的报错捕获到,如果不使用recover函数的话遇到panic程序就会终止,用上的话程序并不会立即终止。相反,程序的控制权将会返回给主函数并得以继续执行

注意:利用recover处理panic指令,必须利用defer在panic之前声明,否则当panic时,recover无法捕获到panic,无法防止panic扩散

defer函数会放入一个栈,在return或panic或程序结束后执行,

func recoveryFunction() {
   if recoveryMessage := recover(); recoveryMessage != nil {
       fmt.Println("aaa", recoveryMessage)
   }
   fmt.Println("This is recovery function...")
}
func executePanic() {
    // 这样写效果是一样的,
   //defer func() {
   //    if e := recover(); e != nil{
   //        fmt.Println("输出panic:", e)
   //    }
   //}()
   defer recoveryFunction()
   // 一旦遇到panic就会执行之前defer的函数,panic后的代码不再执行,
   panic("This is Panic Situation")
   fmt.Println("The function executes Completely")
}
func main() {
   executePanic()
   fmt.Println("Main block is executed completely...")
}
View Code

http://wen.topgoer.com/blog-42.html

https://golangtc.com/t/5cd977eab17a82478bd85fa4

https://blog.csdn.net/chenbaoke/article/details/41966827

原文地址:https://www.cnblogs.com/xxswkl/p/14250302.html