问题
Is there some crossplatform c-library for exception handling (to implement try / catch in C)?
I'm also looking for documentation how it's realized in c++ (how the interrupts are masking or something like this)
回答1:
You can try exceptions4c; it's an exception handling library in ANSI C that supports: throw, try, catch, finally and a few more goodies. For example, it supports the Dispose pattern, so you can automatically release resources. You can also handle signals (such as SIGFPE and SIGSEGV) as if they were exceptions.
It's implemented on top of setjmp and longjmp (standard C library), and it's free software, so you can read and modify the source code.
Oh, by the way, I'm the author :) Please take a look at it, and compare it against other alternatives to see which fits you most.
回答2:
One way to accomplish similar results to C++ exception handling is to use setjmp and longjmp. See the Wikipedia page for a trivial example: http://en.wikipedia.org/wiki/Setjmp.h. Check out the source for the Lua interpreter for a real-world example.
Note that this will NOT be a true implementation of try/catch in the sense that you can call your library from C++ and get real exceptions.
回答3:
The OSSP ex library would seem to satisfy your requirements. It exploits context switching facilities, and is thread safe. Well written and documented, like all the OSSP components.
回答4:
XXL is one such library.
回答5:
Try this.
#define TRY char *__exc_message = NULL; do
#define THROW(exc) { __exc_message = exc; break; }
#define CATCH(exc) while(0); if(__exc_message != NULL) { exc = __exc_message;
#define FINALLY }
void Test(int a, int b)
{
char *exc = NULL;
TRY
{
if(a < b) THROW("A < B!");
if(a > b) THROW("A > B!");
TRACE_INFO("Ok :-)");
}
CATCH(exc)
{
TRACE_ERROR(exc);
}
FINALLY
{
TRACE_INFO("Finally...");
}
}
来源:https://stackoverflow.com/questions/7661308/exception-handling-library-in-pure-c