Can anyone recommend a good exception library? It needs to be for C not C++. (hence the reason I posted in this forum)
Can anyone recommend a good exception library? It needs to be for C not C++. (hence the reason I posted in this forum)
I'm not aware of any good exception libraries. I've seen numerous implementations, some of them quite good, but not in general purpose library form.
All of the reasonable implementations use a stack of cleanup handlers. They vary in the method used to return control up the execution stack during an exception. Some implementations use explicit returns, and some use longjmp.
The longjmp approach is inherently wrong, and can never be done safely, because of the local-variable-clobber issue. However, in simple cases it is tolerable. Explicit returns can be made somewhat more aesthetic by appropriate wrapper macros. Neither solution even approaches the usability of C++ exceptions.
So no, I can't recommend a specific library, but I can discuss techniques if you want to implement one yourself.
Code://try //{ if (a) do { f( b); } while(1); else do { f(!b); } while(1); //}
How difficult would it be to implement one? Or, more importantly, how long would it take?
Code://try //{ if (a) do { f( b); } while(1); else do { f(!b); } while(1); //}
It's pretty non-trivial; especially if you start considering thread safety issues. The most common approach to implement exception style code in C is just to use gotos (This is what the Linux kernel does).
Code:int foo(void) { int ret_val = ERROR; /* ... */ if(bad_case) goto error; ret_val = SUCCESS; error: /* function cleanup goes here */ return ret_val; }
Code://try //{ if (a) do { f( b); } while(1); else do { f(!b); } while(1); //}
That's pretty much what I meant. In a single threaded app, there can just be a single cleanup stack. In a multi-threaded app, you need to store one per thread, and then have synchronization around whatever container holds all the cleanup stacks. It's not that difficult to implement, but it does add another layer of complexity.Each thread needs its own cleanup stack
I downloaded Exceptions in C to try it out. The problem is it won't compile. I uploaded the three files as attachments. The test0.c file came with Exceptions in C. I made a project with all three files and tried to compile. I got this error message:
`try' undeclared (first use in this function)
any ideas?
The two C files included exception-local.h not exception.h! No wonder it didn't work, it was including the wrong file! Anyway changed it and it works just fine now, it looks like Exceptions in C is just what I need.