1: /* Primitive support for exceptions in C. Coded just for fun
  2:    on 2003-07-13 by admp.
  3:    Use, share and modify under GNU General Public License.

  5:    This header file uses many GCC extensions, and therefore is
  6:    unportable. So use GCC.
  7:  */

  9: /* Generally, this implementation is very limited. All after
 10:    all, there is one MAIN restriction: TRY without EXCEPT
 11:    will not even compile or something strange will happen at run time.
 12:    Anyway, there isn't much point in using TRY without EXCEPT, I think.
 13:  */

 15: #if defined (__EXCEPTION_H__)
 16:   lose!
 17: #endif

 19: #define __EXCEPTION_H__

 21: /* All code is based on this. */
 22: #include <setjmp.h>

 24: /* Prefix for all names here is `__exception_' (and __EXCEPTION_ for
 25:    macros) to leave namespace clean. */

 27: /* Type of exception structure. */
 28: #ifndef __EXCEPTION_TYPE
 29: #  define __EXCEPTION_TYPE             int
 30: #endif

 32: /* This makes exception structure from exception code.
 33:    May use as much arguments as you want. */
 34: #ifndef __EXCEPTION_MAKE
 35: #  define __EXCEPTION_MAKE(code)      code
 36: #endif

 38: /* Function for comparing exception structure with exception
 39:    code. */
 40: #ifndef __EXCEPTION_EQ
 41: #  define __EXCEPTION_EQ(f, b)        ((f) == (b))
 42: #endif

 44: /* The top CATCHER. */
 45: static jmp_buf __exception_catcher;

 47: /* The raised exception.*/
 48: static __EXCEPTION_TYPE __exception;

 50: /* File and line where exception was raised. */
 51: static int __exception_line;
 52: static char *__exception_file;

 54: /* The TRY. */
 55: #define try                                  \
 56:   if (setjmp (__exception_catcher) == 0)

 58: /* The EXCEPT. */
 59: #define except                               \
 60:   else

 62: /* The RAISE (EXCEPTION). */
 63: #define raise(code...)                       \
 64:   do {                                       \
 65:    __exception = __EXCEPTION_MAKE (code);    \
 66:    __exception_line = __LINE__;              \
 67:    __exception_file = __FILE__;              \
 68:    longjmp (__exception_catcher, 1);         \
 69:   } while (0)

 71: /* The ON. */
 72: #define on(code...)                          \
 73:   if (__EXCEPTION_EQ (__exception,           \
 74:         __EXCEPTION_MAKE (code)))