exceptions in C implementieren!?
-
Hi,
Weiss jemand vielleicht, wie man am besten in einem C-Programm
Ausnahme-Faelle abfaengt oder Fehler waerend der runtime so ermittelt, dass man weiss an welcher programm-stelle diese genau entstanden sind (ohne 1000 if-abfragen, die den rueckgabewert einer funktion an x-stellen ueberpruefen!!)danke
-
siehe man: setjmp(3)
hab mal folgendes gecoded
#include <setjmp.h> #include <stdio.h> #include <stdlib.h> struct exception_t { int no; jmp_buf buf; }; struct exception_t NOMEMORY; void init_exceptions(void) { NOMEMORY.no=1; } inline void throw(struct exception_t exception) { longjmp(exception.buf,exception.no); } #define catch(exception,dofunc,doexception) \ { \ int ret=setjmp(exception.buf); \ if(ret==0) \ dofunc \ else if(ret==exception.no) \ doexception \ } void *mymalloc(size_t n) { void *ptr=malloc(n); if(!ptr) throw(NOMEMORY); return ptr; } void foo(void) { free(mymalloc(1000000000000000u)); } int main(void) { init_exceptions(); catch(NOMEMORY, { foo(); }, { fprintf(stderr,"nicht genug speicher!\n"); return 1; }); return 0; }