Source file
test/recover6.go
1
2
3
4
5
6
7
8
9
10
11
12 package main
13
14 var got any
15
16
17
18 func doRecover() any { return recover() }
19
20 func setGot() { got = recover() }
21
22
23 func setGotIndirect() { got = doRecover() }
24
25
26 func mustPanic(name string, f func()) {
27 defer func() {
28 if r := recover(); r != "boom" {
29 panic(name + ": panic did not propagate")
30 }
31 }()
32 f()
33 panic(name + " did not panic")
34 }
35
36
37 func mustRecover(name string, f func()) {
38 defer func() {
39 if r := recover(); r != nil {
40 panic(name + ": panic escaped")
41 }
42 }()
43 f()
44 }
45
46 func main() {
47
48 mustRecover("direct", func() {
49 defer setGot()
50 panic("boom")
51 })
52 if got != "boom" {
53 panic("direct: recover did not see the panic value")
54 }
55
56
57
58 mustPanic("closure", func() {
59 defer func() { got = doRecover() }()
60 panic("boom")
61 })
62 if got != nil {
63 panic("closure: recover returned non-nil")
64 }
65
66
67
68
69 mustPanic("nested", func() {
70 defer setGotIndirect()
71 panic("boom")
72 })
73 if got != nil {
74 panic("nested: recover returned non-nil")
75 }
76
77
78 if r := doRecover(); r != nil {
79 panic("idle: recover returned non-nil")
80 }
81 }
82
View as plain text