blob: 12c25a3126794e653b3b7c0c20b9442091379635 [file] [log] [blame] [view]
Andrew Gerrand5bc444d2014-12-10 11:35:11 +11001(TODO: Add table of contents.)
2
3# Panic
4
5The ` panic ` and ` recover ` functions behave similarly to exceptions and try/catch in some other languages in that a ` panic ` causes the program stack to begin unwinding and ` recover ` can stop it. Deferred functions are still executed as the stack unwinds. If ` recover ` is called inside such a deferred function, the stack stops unwinding and ` recover ` returns the value (as an ` interface{ `}) that was passed to ` panic `. The runtime will also panic in extraordinary circumstances, such as indexing an array or slice out-of-bounds. If a ` panic ` causes the stack to unwind outside of any executing goroutine (e.g. ` main ` or the top-level function given to ` go ` fail to recover from it), the program exits with a stack trace of all executing goroutines. A ` panic ` cannot be ` recover `ed by a different goroutine.
6
7# Usage in a Package
8
9By convention, no explicit panic() should be allowed to cross a package boundary. Indicating error conditions to callers should be done by returning error value. Within a package, however, especially if there are deeply nested calls to non-exported functions, it can be useful (and improve readability) to use panic to indicate error conditions which should be translated into error for the calling function. Below is an admittedly contrived example of a way in which a nested function and an exported function may interact via this panic-on-error relationship.
10
11```
12// A ParseError indicates an error in converting a word into an integer.
13type ParseError struct {
Dave Day0d6986a2014-12-10 15:02:18 +110014 Index int // The index into the space-separated list of words.
15 Word string // The word that generated the parse error.
16 Error error // The raw error that precipitated this error, if any.
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110017}
18
19// String returns a human-readable error message.
20func (e *ParseError) String() string {
Dave Day0d6986a2014-12-10 15:02:18 +110021 return fmt.Sprintf("pkg: error parsing %q as int", e.Word)
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110022}
23
24// Parse parses the space-separated words in in put as integers.
25func Parse(input string) (numbers []int, err error) {
Dave Day0d6986a2014-12-10 15:02:18 +110026 defer func() {
27 if r := recover(); r != nil {
28 var ok bool
29 err, ok = r.(error)
30 if !ok {
31 err = fmt.Errorf("pkg: %v", r)
32 }
33 }
34 }()
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110035
Dave Day0d6986a2014-12-10 15:02:18 +110036 fields := strings.Fields(input)
37 numbers = fields2numbers(fields)
38 return
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110039}
40
41func fields2numbers(fields []string) (numbers []int) {
Dave Day0d6986a2014-12-10 15:02:18 +110042 if len(fields) == 0 {
43 panic("no words to parse")
44 }
45 for idx, field := range fields {
46 num, err := strconv.Atoi(field)
47 if err != nil {
48 panic(&ParseError{idx, field, err})
49 }
50 numbers = append(numbers, num)
51 }
52 return
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110053}
54```
55
56To demonstrate the behavior, consider the following main function:
57```
58func main() {
Dave Day0d6986a2014-12-10 15:02:18 +110059 var examples = []string{
60 "1 2 3 4 5",
61 "100 50 25 12.5 6.25",
62 "2 + 2 = 4",
63 "1st class",
64 "",
65 }
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110066
Dave Day0d6986a2014-12-10 15:02:18 +110067 for _, ex := range examples {
68 fmt.Printf("Parsing %q:\n ", ex)
69 nums, err := Parse(ex)
70 if err != nil {
71 fmt.Println(err)
72 continue
73 }
74 fmt.Println(nums)
75 }
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110076}
77```
78
79# References
80[Defer, Panic and Recover](http://blog.golang.org/2010/08/defer-panic-and-recover.html)
81
82http://golang.org/doc/go_spec.html#Handling_panics
83
84http://golang.org/doc/go_spec.html#Run_time_panics