Go语言内建方法之panic&&recover

  • 处理异常

    • panic 抛出异常
    • recover 捕获异常

      package main
      import (
          "fmt"
      )
      func main() {
          recoverPanic()
      }
      func recoverPanic()  {
          defer coverPanic()                  //捕获异常
          //panic("panic")                    //panic message panic
          //panic(errors.New("error"))        //error message error
          panic(1)                          //unknown panic 1
      }
      func coverPanic()  {
          message := recover()
          switch message.(type) {
          case string:
              fmt.Println("panic message",message)
          case error:
              fmt.Println("error message",message)
          default:
              fmt.Println("unknown panic",message)
          }
      }
      
Last modification:September 23, 2020
如果觉得我的文章对你有用,请随意赞赏