how can I handle exceptions in C?
exception handling in C?
Collapse
X
-
Tags: None
-
-
The way my company does it:Originally posted by manjuscriptshow can I handle exceptions in C?
Every function returns a 0 if function was a success or -1 if the function failed.
If a function was a failure, goto cleanup. Here is some snippets.
[CODE=c]
#define try(x) status = (x); \
if (status < 0){ \
GOTO CATCH; \
} \[/CODE]
Checks the status.
[CODE=c]status = someFunction();
try(status); [/CODE]
Checks if status is ever <0
[CODE=c]CATCH:
cleanUpCode(); [/CODE]
Catch statement.
If you want, instead of just returning -1, you can return anything less than 0 and assign these values different error messages.Comment
-
C does not produce and handle software exceptions in the same way C++ does i.e. no throw, try and catch keywords.Originally posted by manjuscriptshow can I handle exceptions in C?
You can intercept and handle hardware exceptions produced externally to the program.
You use can use setjmp and longjump to handle some exceptions, however to catch them you will have to call the signal function and install a signal (exception) handler. There are 5 - 10 things you can catch.
The only signal I have ever had the need to intercept was floating point errror. This was in a complex maths package. The user selected 2 matrices of chemical elements, these were supposed to match, however if they did not match in some fairly subtle and hard to predetermin ways the resulting matrix calculation produced floatiing point errors (divide by zero IIRC). We used the signal to intercept this error, reset the floating point processor and restart the program (using a longjump) rather than just letting it fall over in a big heap.Comment
-
That doesn't work. It relies on human infallibility, which does not exist. All it takes is one new hire who wasn't at the meeting and the convention is kaput.Originally posted by kreganThe way my company does it:
If the compiler cannot enforece the rule, then the rule is no good. (BTW: this is why naming convenrtions don't work either).Comment
Comment