基本用法

  • recover 位置,需要与 panic 在同一个 goroutine 中
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. defer func() {
  8. if err := recover(); err != nil {
  9. fmt.Println("Recover in main from error:", err)
  10. }
  11. fmt.Println("Execution finished")
  12. }()
  13. go func() {
  14. panic("panic in goroutine")
  15. }()
  16. time.Sleep(1 * time.Second)
  17. }
  • 可在 recover 中再次抛出 panic
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. defer func() {
  7. defer func() {
  8. if err := recover(); err != nil {
  9. fmt.Println("Recover from error:", err)
  10. }
  11. }()
  12. if err := recover(); err != nil {
  13. fmt.Println("Recover from error:", err)
  14. panic("again")
  15. }
  16. }()
  17. panic("whatever")
  18. }