>>23
If you have to allocate more than one pointer:
int foo(size_t size1, size_t size2) {
char* string1;
char* string2;
if (!(string1 = malloc(size1))
goto error;
if (!(string1 = malloc(size2)) {
/* free(string1); */
goto error;
}
return 0;
error:
fprintf(stderr, "%s: malloc: %s\n", __func__, strerror(errno));
free(string1);
free(string2);
return -1;
}
Otherwise you'd have to free all the pointers you allocated before the error in every subsequent
if, which could get ridiculous.
>>24
If you want to get really nasty, take a look at this library I wrote (abridged):
#define throw(type, ...)\
do {\
__throw(type, __FILE__, __func__, __LINE__, __VA_ARGS__);\
longjmp(__ex_jmp_buf, type);\
} while (0)
#define try if (!(__ex_type = setjmp(__ex_jmp_buf)))
#define catch(type) \
else if ((__ex_type != EXCEPTION_NONE) && (type == EXCEPTION_ANY || __ex_type == type)) {\
exception* e = __catch();\
__unthrow();
#define otherwise } else
Example:
#include <exception.h>
int idiv(int numerator, int denominator)
{
if (denominator == 0)
throw(EXCEPTION_DIVISION_BY_ZERO, "Integer division by zero");
return numerator / denominator;
}
int main()
{
try {
idiv(1, 0);
} catch (EXCEPTION_ANY) {
exception_print(e);
} otherwise {
printf("No exceptions occurred.\n");
}
return 0;
}