开发者

Exception handling library in pure C

开发者 https://www.devze.com 2023-04-11 10:50 出处:网络
Is there some crossplatform c-l开发者_运维问答ibrary for exception handling (to implement try / catch in C)?

Is there some crossplatform c-l开发者_运维问答ibrary 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)


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.


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.


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.


XXL is one such library.


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...");
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号