Exception handling library in pure C

只谈情不闲聊 提交于 2020-01-03 16:56:03

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!