libexception is an exception handling library for C. It uses the
longjmp calls to build a stack of jump buffers and exceptions and provides
high level semantics implemented as macros to make exception handling in C
unobtrusive and easy to use.
Error handling is an important issue in programming languages, and it can account for a substantial portion of a project's code. The classic C approach to this problem is return codes. Each function returns a value indicating success or failure. However, with a nontrivial function call hierarchy, this approach clutters the code significantly. Every function must check the return code of every function call it makes and take care of errors. In most cases, the function will merely pass any errors back up to its caller.
Programming languages such as Ada or C++ address this issue with exceptions. Exceptions make it easy to separate error handling from the rest of the code. Intermediate functions can completely ignore errors occurring in functions they call, if they can't handle them anyway.
The solution to this problem is to implement a simple exception-handling library in C.
libexception uses two stacks implemented as a doubly-linked list to record exceptions and jump
buffers needed by
longjmp. The work-flow is as follows:
setjmpand push the resulting
jmp_bufobject onto the tryenv stack.
setjmpreturns zero and the following block is executed. if no exception occured nothing else happens.
- if an exception is raised
throwwill push information about the error onto the exception stack and call
longjmpto jump to the topmost tryenv buffer.
- in this case
setjmpreturns again, but with a non-zero return code and the following
exceptblock is executed.
- an except block consists of zero or more
onblocks to handle a single exception and zero or one
finallyblock to handle a yet unhandled but unknown exception
- if an
onblock handled the exception the exception stack is cleared and nothing else happens.
- if no
onblock handled the exception but a
finallyblock handled the exception the exception stack is cleared and nothing else happens.
- if an unhandled exception is found at the end of an
exceptblock, control is transfered to the next jump buffer (a.k.a
- if there are no more jump buffers available, the default exception handler
is called to print an exception trace to
STDERRand the program will be aborted.
To install libexception call
make and finally
Examples can be found in the test-suite.