Details of the differences between recover and panic in Go

  • 2020-09-28 08:55:12
  • OfStack

concept

panic and recover are two built-in functions of Go that handle errors at the Go runtime.

panic is used to actively throw errors, and recover is used to catch errors thrown by panic.


func main() {
  // capture   abnormal 
  defer func() {
    if p := recover(); p != nil {
      fmt.Printf("panic recover! p: %v", p)
      // Type judgment 
      str, ok := p.(string)
      if ok {
        err := errors.New(str)
        fmt.Println(err)
      } else {
        err := errors.New("panic")
        fmt.Println(err)
      }

    }
  }()
  fmt.Println("hello world")
  add(1, 0)
}

func add(x, y int) int {
  //  Throw an error 
  panic("test")
  z := x / y
  return z
}

Related articles: