4 * Copyright 2006 Develer S.r.l. (http://www.develer.com/)
5 * Copyright 1999 Bernardo Innocenti <bernie@develer.com>
6 * This file is part of DevLib - See README.devlib for information.
9 * \brief C++-like structured exception handling for C programs
12 * \author Bernardo Innocenti <bernie@develer.com>
14 #ifndef MWARE_EXCEPT_H
15 #define MWARE_EXCEPT_H
17 #include <cfg/debug.h>
21 #define EXCEPT_CONTEXTS 8
24 * A stack of jump buffers used to record try sites
25 * so they can be reached from throw sites.
27 * The stack contains return points for each nested
28 * context. jmp_buf's are pushed into the stack at
29 * try points and popped out when the try block ends
30 * normally or when an exception is thrown.
32 extern jmp_buf except_stack[EXCEPT_CONTEXTS];
33 extern int except_top;
36 # define PUSH_EXCEPT ASSERT(except_top < EXCEPT_CONTEXTS), setjmp(except_stack[except_top++]))
37 # define POP_EXCEPT (ASSERT(except_top > 0), --except_top)
38 # define DO_EXCEPT (ASSERT(except_top > 0), longjmp(except_stack[--except_top], true))
40 # define PUSH_EXCEPT (setjmp(except_stack[except_top++]))
41 # define POP_EXCEPT (--except_top)
42 # define DO_EXCEPT (longjmp(except_stack[--except_top], true))
46 * Jump buffer to use when throwing an exception or aborting an operation
48 * User code can throw exceptions like this:
51 * void a_function_throwing_exceptions(void)
53 * if (some_error_condition)
58 * Catching exceptions (brackets are optional):
63 * void a_function_catching_an_exception(void)
67 * printf("Entered try block\n");
68 * a_function_throwing_exceptions();
69 * printf("Survived execution of critical code\n");
73 * printf("Exception caught!\n");
79 * Simple syntax when you don't need to do anything when catching an excaption:
83 * printf("Entered try block\n");
84 * a_function_throwing_exceptions();
85 * printf("Survived execution of critical code\n");
89 * You also need to declare the exception stack once in
90 * your global declarations:
95 #define TRY if (PUSH_EXCEPT) { {
96 #define TRY_END } POP_EXCEPT; }
97 #define CATCH } POP_EXCEPT; } else {
99 #define THROW DO_EXCEPT
102 #define EXCEPT_DEFINE \
103 jmp_buf except_stack[EXCEPT_CONTEXTS]; \
106 #endif /* MWARE_EXCEPT_H */