-
Notifications
You must be signed in to change notification settings - Fork 31
/
try.go
56 lines (49 loc) · 813 Bytes
/
try.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package try
const rethrow_panic = "_____rethrow"
type (
E interface{}
exception struct {
finally func()
Error E
}
)
func Throw() {
panic(rethrow_panic)
}
func This(f func()) (e exception) {
e = exception{nil, nil}
// catch error in
defer func() {
e.Error = recover()
}()
f()
return
}
func (e exception) Catch(f func(err E)) {
if e.Error != nil {
defer func() {
// call finally
if e.finally != nil {
e.finally()
}
// rethrow exceptions
if err := recover(); err != nil {
if err == rethrow_panic {
err = e.Error
}
panic(err)
}
}()
f(e.Error)
} else if e.finally != nil {
e.finally()
}
}
func (e exception) Finally(f func()) (e2 exception) {
if e.finally != nil {
panic("finally was only set")
}
e2 = e
e2.finally = f
return
}