Exception handling is C language is done by checking variables or output/return values of the functions. Standard non-void C function returns status code as integer. Zero value indicates a success. Non-zero value indicates failure and the value represents the error code.
Exception handling using return value:
In this example Connect_server() connects the client to the server over a given network.
Syntax:
int connect_server(void);
Return:
zero indicates success.
Non-zero indicates error and return value is the error code.
Exception handling Code:
int error_code = 0; error_code = connect_server(); if(error_code != 0) { printf("error establishing connection to the server!!\n"); printf("Error code %d", error_code); exit(error_code); } else { /*add next steps here*/ }
Returning exception to the operating system:
main() function is also a good example in this context.
main() returns a zero(0) to the operating system to inform that process has been successfully terminated.
main() returns a non-zero value when any exception has occurred.
Code:
int main(int argc, char *argv[]) { int error_code = 0; error_code = connect_server(); if(error_code != 0) { printf("error establishing connection to the server!!\n"); printf("Error code %d", error_code); return error_code;/*error code to OS*/ } else { /*add next steps here*/ return 0;/*success code to OS*/ } }
Checking NULL pointer:
Another checking that may be performed with pointer variable is NULL checking. Pointers are valid when the value is NULL. If any function returns a valid pointer it should not be NULL. If NULL is returned, then there must be some dynamic memory allocation problem.
Example:
char *name = NULL; name = (char *)malloc(10); if(name == NULL) { printf("Not enough memory to run this application"); exit(-1); }
setjmp-longjmp:
C language provides a mechanism of setjmp-longjmp to achieve a try-catch style exception handling. Please visit next page to get the details on this topic.
About our authors: Team EQA
You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.