Source file
doc/progs/defer2.go
1
2
3
4
5
6
7 package main
8
9 import "fmt"
10 import "io"
11 import "os"
12
13 func main() {
14 f()
15 fmt.Println("Returned normally from f.")
16 }
17
18 func f() {
19 defer func() {
20 if r := recover(); r != nil {
21 fmt.Println("Recovered in f", r)
22 }
23 }()
24 fmt.Println("Calling g.")
25 g(0)
26 fmt.Println("Returned normally from g.")
27 }
28
29 func g(i int) {
30 if i > 3 {
31 fmt.Println("Panicking!")
32 panic(fmt.Sprintf("%v", i))
33 }
34 defer fmt.Println("Defer in g", i)
35 fmt.Println("Printing in g", i)
36 g(i + 1)
37 }
38
39
40
41
42 func CopyFile(dstName, srcName string) (written int64, err error) {
43 src, err := os.Open(srcName)
44 if err != nil {
45 return
46 }
47 defer src.Close()
48
49 dst, err := os.Create(dstName)
50 if err != nil {
51 return
52 }
53 defer dst.Close()
54
55 return io.Copy(dst, src)
56 }
57
58
59
View as plain text