Error handling style in C
pixelstech.net
Error handling style in C
1–10 of 45 posts
Re: Error handling style in C
#2goto :3
Re: Error handling style in C
#3It lacks 4th method that I find the best: with long jumps. I mean for example:
jmp_buf errbuf;
int result;
if( !( result = set_jmp ) )
{
/* Code to do on fail. Result may be some error code */
}
else
{
someaction( par1, par2, ..., errbuf);
anotheraction( par1, par2, ..., errbuf);
/* Etc. */
}
errbuf might be global if you prefer, but I'd rather avoid them. When something is wrong called function calls longjmp(errbuf, errorcode).Re: Error handling style in C
#4the goto style.
you can escape goto by the following trick:
do
{
if (!do_something( bar )) {
break;
}
if (!init_stuff( bar )) {
break;
}
if (!prepare_stuff( bar )) {
break;
}
return do_the_thing( bar );
}while(0);
return 0;Re: Error handling style in C
#5Why goto is bad? Again this "structured programming" bullshit. Kernel uses 2 a lot to handle errors like here [1].
[1] https://github.com/torvalds/linux/blob/master/mm/shmem.c#L99...
Re: Error handling style in C
#6There's the 5th method that I tend to use:
if (!init_stuff(bar)) {
return FALSE;
}
if (!do_the_thing(bar)) {
return FALSE;
}
return TRUE;Re: Error handling style in C
#7LoseThos has exceptions.
Re: Error handling style in C
#8Why goto is bad? Again this "structured programming" bullshit. Kernel uses 2 a lot to handle errors like here [1]. [1] https://github.com/torvalds/linux/blob/master/mm/shmem.c#L99...
THANK you. I was thinking the exact same thing. This is seen all over the kernel, and I found it to be a very readable, simple solution, and a very good use of goto.
Re: Error handling style in C
#9A forward jumping goto (to a single target inside a function) is just perfect for C error handling code. Don't be misguided by a silly principle of goto's being always bad. They get the job done in the cleanest possible way, so you should use them for doing cleanups.
The examples did not have any resources to clean up, and that is what makes error handling in C painful. In the absence of any cleanup routines, this will do:
return (
do_something() == SUCCESS &&
do_something_else() == SUCCESS &&
do_final_thing() == SUCCESS) ? SUCCESS : FAILURE;
Of course, once you add resources to clean up or error codes that are meaningful (not just success/fail) error handling gets more painful.You should not try to perfect something as mundane as error handling. Just write the damn code and get over it.
Re: Error handling style in C
#10Why goto is bad? Again this "structured programming" bullshit. Kernel uses 2 a lot to handle errors like here [1]. [1] https://github.com/torvalds/linux/blob/master/mm/shmem.c#L99...
In general, gotos are bad. For error handling in C, they're perfect. Just don't jump backwards in code.