defer2.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // This file contains the code snippets included in "Defer, Panic, and Recover."
  5. package main
  6. import "fmt"
  7. import "io" // OMIT
  8. import "os" // OMIT
  9. func main() {
  10. f()
  11. fmt.Println("Returned normally from f.")
  12. }
  13. func f() {
  14. defer func() {
  15. if r := recover(); r != nil {
  16. fmt.Println("Recovered in f", r)
  17. }
  18. }()
  19. fmt.Println("Calling g.")
  20. g(0)
  21. fmt.Println("Returned normally from g.")
  22. }
  23. func g(i int) {
  24. if i > 3 {
  25. fmt.Println("Panicking!")
  26. panic(fmt.Sprintf("%v", i))
  27. }
  28. defer fmt.Println("Defer in g", i)
  29. fmt.Println("Printing in g", i)
  30. g(i + 1)
  31. }
  32. // STOP OMIT
  33. // Revised version.
  34. func CopyFile(dstName, srcName string) (written int64, err error) {
  35. src, err := os.Open(srcName)
  36. if err != nil {
  37. return
  38. }
  39. defer src.Close()
  40. dst, err := os.Create(dstName)
  41. if err != nil {
  42. return
  43. }
  44. defer dst.Close()
  45. return io.Copy(dst, src)
  46. }
  47. // STOP OMIT