Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error handling strategies in C?

Tags:

c

Given the code below:

typedef struct {int a;} test_t;

arbitrary_t test_dosomething(test_t* test) {
    if (test == NULL) {
        //options:
        //1. print an error and let it crash
          //e.g. fprintf(stderr, "null ref at %s:%u", __FILE__, __LINE__);
        //2. stop the world
          //e.g. exit(1);
        //3. return (i.e. function does nothing)
        //4. attempt to re-init test
    }
    printf("%d", test->a); //do something w/ test
}

I want to get a compiler error if test is ever NULL, but I guess that's not possible in C. Since I need to do null checking at runtime, what option is the most proper way to handle it?

like image 590
Leo Avatar asked May 03 '10 01:05

Leo


People also ask

Does C have error handling?

C does not provide direct support for error handling (also known as exception handling). By convention, the programmer is expected to prevent errors from occurring in the first place, and test return values from functions.


4 Answers

If you never want the function to be called with a null pointer (i.e., the pointer not being null is a precondition to calling the function), you can use an assertion at the top of the function:

assert(test != NULL);

This can help you when debugging to find places in your code where you are calling the function with a null pointer.

like image 66
James McNellis Avatar answered Oct 28 '22 06:10

James McNellis


We really can't categorically answer this question. It depends highly on what the software is going to be used for. If it's providing radiation, you would want it to print the error and exit(1);. If you're writing a business app, you probably want to log an error and just return. It's all about the context.

like image 30
C. Ross Avatar answered Oct 28 '22 05:10

C. Ross


Use setjmp.

http://en.wikipedia.org/wiki/Setjmp.h

http://aszt.inf.elte.hu/~gsd/halado_cpp/ch02s03.html

#include <setjmp.h>
#include <stdio.h>

jmp_buf x;

void f()
{
    longjmp(x,5); // throw 5;
}

int main()
{
    // output of this program is 5.

    int i = 0;

    if ( (i = setjmp(x)) == 0 )// try{
    {
        f();
    } // } --> end of try{
    else // catch(i){
    {
        switch( i )
        {
        case  1:
        case  2:
        default: fprintf( stdout, "error code = %d\n", i); break;
        }
    } // } --> end of catch(i){
    return 0;
}
like image 31
Amir Saniyan Avatar answered Oct 28 '22 06:10

Amir Saniyan


I would use an assert at the beginning of the function:

arbitrary_t test_dosomething(test_t* test) {
    assert(test != NULL);
    printf("%d", test->a); //do something w/ test
}

You won't get a compiler error. But when in development (debugging) your program will halt and point you to that particular assert in the code.

like image 42
Pablo Santa Cruz Avatar answered Oct 28 '22 05:10

Pablo Santa Cruz