Simple library for exception handling in C. Uses dynamic memory allocation to create exceptions in the heap. Each exception is related to a function/module. It contains the name of the function, an integer that specifies the kind of exception and a human readable description of what happened. If it was related or generated by another exception in a lower level function/module, it can contain a pointer to it. This way a linked list of exception can be generated. This linked list describes what happened in each function level, from higher to lower.
/* define a low level function that sums two numbers and can generate an exception */
exc sumOfPositiveNumbers(int a, int b, int* c){
if (a<=0) {
return exc_throw(1, "sumOfPositiveNumbers", "a is negative"); // throws an exception with identifier 1
}else if (b<=0)
{
return exc_throw(2, "sumOfPositiveNumbers", "b is negative"); // throws an exception
} else {
*c = a+b;
return EXC_NONE; // returns no exception
}
}
/* define a higher level function that calculates the average of two numbers. It can generate exceptions that are generated by the lower level function sum */
exc averageOfNumbers(int a, int b, int* c){
int result;
exc exception = sumOfPositiveNumbers(a, b, &result);
if (exception != EXC_NONE) {
return exc_add_and_throw(exception, 1, "averageOfNumbers", "error in sum function");
}
*c = result/2;
return EXC_NONE;
}
int main(void){
int c;
exc exception = averageOfNumbers(-1, 1, &c); // this should generate the exception
exc_print(exception); // prints to console the exception
exc_free(exception); // since the exceptions linked list is generated in the heap, always remember to free
}
Command line output:
An exception occurred, trace:
-> In function 'averageOfNumbers': error in sum function.
-> In function 'sumOfPositiveNumbers': a is negative.