Examples of panic and recover function usage in go language

  • 2020-07-21 08:20:18
  • OfStack

Golang has two built-in functions panic() and recover() , which is used to report and catch program errors at runtime. Unlike error, ES5en-ES6en 1 is typically used inside functions. Be careful not to abuse ES7en-ES8en, which can cause performance problems. I usually use it only for unknown inputs and unreliable requests.

Error handling of golang: When an exception or encounter occurs during execution of a function panic() , the normal statement terminates immediately, the defer statement is executed, the exception is reported, and goroutine exits. If the recover() function is used in defer, an error message is caught and the error message terminates the report.

Look at the code:


package main
import "fmt"
func main(){
  defer func(){
    fmt.Println("c")
    // if err := recover(); err != nil{
    //   fmt.Println(err)
    // }else{
    //   fmt.Println("hehe")
    // }
    // if err := recover(); err != nil{
    //   fmt.Println(err)
    // }else{
    //   fmt.Println("haha")
    // }
    fmt.Println("d")
  }()
  f()
  defer func(){
    fmt.Println("e")
  }()
}
func f(){
  fmt.Println("a")
  panic(10000)
  fmt.Println("b")
  fmt.Println("f")
}

Results:

[

ubuntu@VM-0-15-ubuntu:~/taoge/go$ go run test.go
a
c
d
panic: 10000
goroutine 1 [running]:
panic(0x4b8480, 0xc82000a2c0)
/usr/lib/go-1.6/src/runtime/panic.go:481 +0x3e6
main.f()
/home/ubuntu/taoge/go/test.go:34 +0x115
main.main()
/home/ubuntu/taoge/go/test.go:25 +0x35
exit status 2
ubuntu@VM-0-15-ubuntu:~/taoge/go$

]

Look at the code:


package main
import "fmt"
func main(){
  defer func(){
    fmt.Println("c")
    if err := recover(); err != nil{
      fmt.Println(err)
    }else{
      fmt.Println("hehe")
    }
    if err := recover(); err != nil{
      fmt.Println(err)
    }else{
      fmt.Println("haha")
    }
    fmt.Println("d")
  }()
  f()
  defer func(){
    fmt.Println("e")
  }()
}
func f(){
  fmt.Println("a")
  panic(10000)
  fmt.Println("b")
  fmt.Println("f")
}

Results:

[

ubuntu@VM-0-15-ubuntu:~/taoge/go$ go run test.go
a
c
10000
haha
d
ubuntu@VM-0-15-ubuntu:~/taoge/go$

]

Feel it.

conclusion


Related articles: