I typed this into google but only found howtos in C++,
how to do it in C?
I typed this into google but only found howtos in C++,
how to do it in C?
There are no exceptions in C. Exceptions defined in C++ and other languages though.
Exception handling in C++ is specified in the C++ standard "S.15 Exception handling", there is no equivalent section in the C standard.
C doesn't have exceptions.
There are various hacky implementations that try to do it (one example at: http://adomas.org/excc/).
Plain old C doesn't actually support exceptions natively.
You can use alternative error handling strategies, such as:
FALSE
and using a last_error
variable or function.See http://en.wikibooks.org/wiki/C_Programming/Error_handling.
C doesn't support exceptions. You can try compiling your C code as C++ with Visual Studio or G++ and see if it'll compile as-is. Most C applications will compile as C++ without major changes, and you can then use the try... catch syntax.
On Win with MSVC there's _try ... __except ...
but it's really horrible and you don't want to use it if you can possibly avoid it. Better to say that there are no exceptions.
In C you should use setjmp/longjmp
defined in setjmp.h
. Example from Wikipedia
#include <stdio.h>
#include <setjmp.h>
static jmp_buf buf;
void second(void) {
printf("second\n"); // prints
longjmp(buf,1); // jumps back to where setjmp
// was called - making setjmp now return 1
}
void first(void) {
second();
printf("first\n"); // does not print
}
int main() {
if ( ! setjmp(buf) ) {
first(); // when executed, setjmp returns 0
} else { // when longjmp jumps back, setjmp returns 1
printf("main"); // prints
}
return 0;
}
Note: I would actually advise you not to use them as they work awful with C++ (destructors of local objects wouldn't get called) and it is really hard to understand what is going on. Return some kind of error instead.