Try catch statements in C
You use goto in C for similar error handling situations.
That is the closest equivalent of exceptions you can get in C.
C itself doesn't support exceptions but you can simulate them to a degree with setjmp
and longjmp
calls.
static jmp_buf s_jumpBuffer;
void Example() {
if (setjmp(s_jumpBuffer)) {
// The longjmp was executed and returned control here
printf("Exception happened here\n");
} else {
// Normal code execution starts here
Test();
}
}
void Test() {
// Rough equivalent of `throw`
longjmp(s_jumpBuffer, 42);
}
This website has a nice tutorial on how to simulate exceptions with setjmp
and longjmp
- http://www.di.unipi.it/~nids/docs/longjump_try_trow_catch.html