exception handling mechanism

R

Ralph A. Moeritz

Hello,

I'd like to implement an exception handling mechanism
in my C programs. Up to now I have been using a local
error handling scheme where errors are handled (when
appropriate) in the lowest-level functions eg.

char *
foo (void)
{
int err = 0; /* (error flag: 1=set) */
char *str = xmalloc (BUF_LEN);

int ret = do_something (str);
if (!ret)
{
++err;
goto clean_up;
}

clean_up:
if (err)
{
/* handle error */
}

return str;
}

void
bar (void)
{
char *s = foo ();
/* ... */
}

What this sheme lacks is a way for the called function to pass error
information back to the calling function so that it can deal with it
in appropriate situations. I've heard of people implementing TRY,
CATCH, THROW using setjmp & longjmp, but I've never seen any code
for this...

Regards,
Ralph
 
F

Fred L. Kleinschmidt

Ralph A. Moeritz said:
Hello,

I'd like to implement an exception handling mechanism
in my C programs. Up to now I have been using a local
error handling scheme where errors are handled (when
appropriate) in the lowest-level functions eg.

char *
foo (void)
{
int err = 0; /* (error flag: 1=set) */
char *str = xmalloc (BUF_LEN);

int ret = do_something (str);
if (!ret)
{
++err;
goto clean_up;
}

clean_up:
if (err)
{
/* handle error */
}

return str;
}

void
bar (void)
{
char *s = foo ();
/* ... */
}

What this sheme lacks is a way for the called function to pass error
information back to the calling function so that it can deal with it
in appropriate situations. I've heard of people implementing TRY,
CATCH, THROW using setjmp & longjmp, but I've never seen any code
for this...

Regards,
Ralph

Why make life complicated? There are two extremely simple solutions:
1)
int foo( char **result ) {
if ( result == NULL ) return ERROR_1; /* #define ERROR_1 somewhere */
*result = malloc(...);
...
if (error) return ERROR_2;
...
return 0;
}

void bar(void) {
char *s;
int status = foo(&s);
}

2)
char *foo( int *status )
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top