1 | #include "exception.h" |
---|
2 | |
---|
3 | #include <stdio.h> |
---|
4 | |
---|
5 | // Translation Helpers: |
---|
6 | #define CLEANUP(function) \ |
---|
7 | struct __cleanup_hook __hidden_hook __attribute__((cleanup(function))) |
---|
8 | |
---|
9 | |
---|
10 | // Local Print On Exit: |
---|
11 | struct raii_base_type { |
---|
12 | const char * area; |
---|
13 | }; |
---|
14 | |
---|
15 | void raii_dtor(struct raii_base_type * this) { |
---|
16 | printf("Exiting: %s\n", this->area); |
---|
17 | } |
---|
18 | |
---|
19 | #define raii_t __attribute__((cleanup(raii_dtor))) struct raii_base_type |
---|
20 | |
---|
21 | // Runtime code (post-translation). |
---|
22 | void terminate(int except_value) { |
---|
23 | raii_t a = {"terminate function"}; |
---|
24 | __throw_terminate(except_value); |
---|
25 | printf("terminate returned\n"); |
---|
26 | } |
---|
27 | |
---|
28 | void resume(int except_value) { |
---|
29 | raii_t a = {"resume function"}; |
---|
30 | __throw_resume(except_value); |
---|
31 | printf("resume returned\n"); |
---|
32 | } |
---|
33 | |
---|
34 | // Termination Test: Two handlers: no catch, catch |
---|
35 | void bar() { |
---|
36 | void bar_try1() { |
---|
37 | terminate(4); |
---|
38 | } |
---|
39 | void bar_catch1(int index, exception except) { |
---|
40 | switch(except) { |
---|
41 | case 1: |
---|
42 | printf("bar caught exception.\n"); |
---|
43 | break; |
---|
44 | default: |
---|
45 | printf("INVALID INDEX in bar: %d\n", except); |
---|
46 | } |
---|
47 | } |
---|
48 | int bar_match1(exception except) { |
---|
49 | if (3 == except) { |
---|
50 | return 1; |
---|
51 | } else { |
---|
52 | return 0; |
---|
53 | } |
---|
54 | } |
---|
55 | __try_terminate(bar_try1, bar_catch1, bar_match1); |
---|
56 | } |
---|
57 | |
---|
58 | void foo() { |
---|
59 | void foo_try1() { |
---|
60 | bar(); |
---|
61 | } |
---|
62 | void foo_catch1(int index, exception except) { |
---|
63 | switch(except) { |
---|
64 | case 1: |
---|
65 | printf("foo caught exception 4.\n"); |
---|
66 | break; |
---|
67 | case 2: |
---|
68 | printf("foo caught exception 2.\n"); |
---|
69 | break; |
---|
70 | default: |
---|
71 | printf("INVALID INDEX in foo: %d\n", except); |
---|
72 | } |
---|
73 | } |
---|
74 | int foo_match1(exception except) { |
---|
75 | if (4 == except) { |
---|
76 | return 1; |
---|
77 | } else if (2 == except) { |
---|
78 | return 2; |
---|
79 | } else { |
---|
80 | return 0; |
---|
81 | } |
---|
82 | } |
---|
83 | __try_terminate(foo_try1, foo_catch1, foo_match1); |
---|
84 | } |
---|
85 | |
---|
86 | int main(int argc, char * argv[]) { |
---|
87 | raii_t a = {"main function"}; |
---|
88 | |
---|
89 | foo(); |
---|
90 | } |
---|