Created
May 17, 2013 09:12
-
-
Save Moddus/5597952 to your computer and use it in GitHub Desktop.
Example error handling in c.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* error type | |
*/ | |
typedef int state_t; | |
/** | |
* error states | |
*/ | |
#define STATE_SUCCESS (0) | |
#define STATE_NULL_PTR (1) | |
/** | |
* macros for error handling | |
*/ | |
#define ERRSR(state) if( (s=state) ) { return s; } | |
#define ERRSPR( PTR, STATECODE ) \ | |
ERRSR( ( NULL == (PTR) ? STATECODE : STATE_SUCCESS) ) \ | |
#define ERRSB(state) if( (s=state) ) { break; } | |
#define ERRSPB( PTR, STATECODE ) \ | |
ERRSB( ( NULL == (PTR) ? STATECODE : STATE_SUCCESS) ) \ | |
state_t methodA() | |
{ | |
state_t s = STATE_SUCCESS; | |
char *str = NULL; | |
do | |
{ | |
str = (char*) malloc(...); | |
ERRSPB(str, STATE_NULL_PTR); | |
//do something | |
ERRSPB(...); | |
} | |
while(0); | |
//cleanup | |
if ( NULL != str ) | |
{ | |
free(str); | |
} | |
return s; | |
} | |
state_t methodB() | |
{ | |
state_t s = STATE_SUCCESS; | |
char *str = NULL; | |
str = (char*) malloc(...); | |
ERRSPR(str, STATE_NULL_PTR); | |
//do something | |
ERRSPR(...); | |
return s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment