Error handling styles in C?

Possible duplicate:
Error handling in C code

Hello people. I use C for some small projects, and I see how, since it does not have special error handling constructs, I have to pollute my algorithm with additional conditional blocks. My question is how do you prefer to deal with errors and justify why. I am torn between two ways ... if you have a third, send it. Thank.

///////////////////////////////////////////
// method 1

// stuff that can go wrong;

if (test1 == failed)
{
    // print error;
    // exit;
}
else
{
    // more stuff that can go wrong;

    if (test2 == failed)
    {
        // print error;
        // exit;
    }
    else
    {
        // ... and so on...
    }
}

///////////////////////////////////////////
// method 2

// stuff that can go wrong;

if (test1 == failed)
{
    // print error;
    // exit;
}

// more stuff that can go wrong;

if (test2 == failed)
{
    // print error;
    // exit;
}

// ... and so on...
+3
source share
4 answers

Some people disagree with me about this, but I use goto's. Inside each function at the end, I have a block at the end that looks like this

if (0)
{
ERROR:
  // Handle errors, and exit/return after potentially freeing resources
}

if (something_bad) goto ERROR; elses .

goto's, . , goto, :

#define LOCAL_ASSERT(COND) if (COND) { \
  /* Handle errors, and exit/return after potentially freeing resources */ \
}

, #undef LOCAL_ASSERT . , .

LOCAL_ASSERT(cond) .

:, , , . , ( ). , - .

// method 1
if (error) goto ERROR; // no else

// method 2
LOCAL_ASSERT(cond);

Elses , .

+5

, , , ( ):

const Bool funcFoo(int someval, int someval2, int someval3)
{
  if(someval == okval)
  { // We're ok
    if(someval2 == okval2)
    { // Still ok.
      if(someval3 == okval3)
      { // Yippee!  We made it!
        return True;  // <===== ONLY SUCCESS RETURN POINT
      }
    }
  }
  // Houston, we had a problem.
  return False;  // <===== ONLY FAIL RETURN POINT
}

, "else", , :

const Bool funcFoo(int someval, int someval2, int someval3)
{
  if(someval == okval)
  { // We're ok
    if(someval2 == okval2)
    { // Still ok.
      if(someval3 == okval3)
      { // Yippee!  We made it!
        return True;  // <===== ONLY SUCCESS RETURN POINT
      }
      else
      { // someval3 is bad.
        //...maybe handle, not return.
      }
    }
    else
    { // someval2 is bad.
      // ...maybe handle, not return.
    }
  }
  else
  { // someval is bad.
    // ...maybe handle, not return.
  }
  // Houston, we had a problem.
  return False;  // <===== ONLY FAIL RETURN POINT
}

, :

  • . , ( ).
  • "else" , point #ifdef _DEBUG ... #endif
  • "" , , , .
  • ( ) . .
+1

- :

if (test1 == failed)
{
    // print error;
    // exit;
}
else if (test2 == failed)
{
    // print error;
    // exit;
}
else
{
    // ... and so on...
}

. , , , , , ; .

0

2. , 1 "" .

0

All Articles