一.recover

  • recover()表示恢复程序的panic(),让程序正常运行
  • recover()是和panic(v)一样都是builtin中函数,可以接收panic的信息,恢复程序的正常运行
  1. // The recover built-in function allows a program to manage behavior of a
  2. // panicking goroutine. Executing a call to recover inside a deferred
  3. // function (but not any function called by it) stops the panicking sequence
  4. // by restoring normal execution and retrieves the error value passed to the
  5. // call of panic. If recover is called outside the deferred function it will
  6. // not stop a panicking sequence. In this case, or when the goroutine is not
  7. // panicking, or if the argument supplied to panic was nil, recover returns
  8. // nil. Thus the return value from recover reports whether the goroutine is
  9. // panicking.
  10. func recover() interface{}
  • recover()一般用在defer内部,如果没有panic信息返回nil,如果有panic,recover会把panic状态取消
  1. func main() {
  2. defer func() {
  3. if error:=recover();error!=nil{
  4. fmt.Println("出现了panic,使用reover获取信息:",error)
  5. }
  6. }()
  7. fmt.Println("11111111111")
  8. panic("出现panic")
  9. fmt.Println("22222222222")
  10. }
  • 输出
  1. 11111111111
  2. 出现了panic,使用reover获取信息: 出现panic

二.函数调用过程中panic和recover()

  • recover()只能恢复当前函数级或当前函数调用函数中的panic(),恢复后调用当前级别函数结束,但是调用此函数的函数可以继续执行.
  • panic会一直向上传递,如果没有recover()则表示终止程序,但是碰见了recover(),recover()所在级别函数表示没有panic,panic就不会向上传递
  1. func demo1(){
  2. fmt.Println("demo1上半部分")
  3. demo2()
  4. fmt.Println("demo1下半部分")
  5. }
  6. func demo2(){
  7. defer func() {
  8. recover()//此处进行恢复
  9. }()
  10. fmt.Println("demo2上半部分")
  11. demo3()
  12. fmt.Println("demo2下半部分")
  13. }
  14. func demo3(){
  15. fmt.Println("demo3上半部分")
  16. panic("在demo3出现了panic")
  17. fmt.Println("demo3下半部分")
  18. }
  19. func main() {
  20. fmt.Println("程序开始")
  21. demo1()
  22. fmt.Println("程序结束")
  23. }