Andrew Gerrand | 49d82b4 | 2011-12-12 13:15:29 +1100 | [diff] [blame] | 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 | |
Shenghou Ma | cd54e44 | 2012-01-12 07:55:23 -0800 | [diff] [blame] | 5 | // This file contains the code snippets included in "Defer, Panic, and Recover." |
Andrew Gerrand | 49d82b4 | 2011-12-12 13:15:29 +1100 | [diff] [blame] | 6 | |
| 7 | package main |
| 8 | |
| 9 | import "fmt" |
| 10 | import "io" // OMIT |
| 11 | import "os" // OMIT |
| 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 | } |
Andrew Gerrand | 468e692 | 2012-01-09 20:05:34 +1100 | [diff] [blame] | 38 | |
Andrew Gerrand | 49d82b4 | 2011-12-12 13:15:29 +1100 | [diff] [blame] | 39 | // STOP OMIT |
| 40 | |
| 41 | // Revised version. |
| 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 | } |
Andrew Gerrand | 468e692 | 2012-01-09 20:05:34 +1100 | [diff] [blame] | 57 | |
Andrew Gerrand | 49d82b4 | 2011-12-12 13:15:29 +1100 | [diff] [blame] | 58 | // STOP OMIT |