Question

Possible Duplicate:
ANSI C equivalent of try/catch?

Is there a way to skip critical code ? More or less like try-catch in modern programming languages. Just now I'm using this technique to spot errors:

bindSignals();
{
    signal(SIGFPE, sigint_handler);
    // ...
}

int main(void)
{
    bindsignals();
    int a = 1 / 0; // division by zero, I want to skip it
    return 0;
}

The problem is if I don't exit the program in the handler I get the very same error again and again. If possible I would like to avoid goto. I also heard about "longjump" or something. Is it worth to (learn to) use ?

Was it helpful?

Solution 3

I'm done. That's how my code looks like now. Almost like Java and C#.

#include <setjmp.h>

jmp_buf jumper;

#define try           if (setjmp(jumper) == 0)
#define catch         else
#define skip_to_catch longjmp(jumper, 0)

static void sigint_handler(int sig)
{
    skip_to_catch;
}

int main(void)
{
    // init error handling once at the beginning
    signal(SIGFPE,  sigint_handler);

    try
    {
        int a = 1 / 0;
    }
    catch
    {
        printf("hello error\n");
    }
    return 0;
}

OTHER TIPS

Well, you can probably accomplish something like that using longjmp(), yes.

Possibly with the "help" of some macros. Note the comment on the manual page, though:

longjmp() and siglongjmp() make programs hard to understand and maintain. If possible an alternative should be used.

I'll throw my two cents in on this. C does not have a mechanism like the try/catch that other languages support. You can build something using setjmp() and longjmp() that will be similar, but nothing exactly the same.

Here's a link showing a nice way of using setjmp and longjmp to do what you were thinking; and a code snippet from the same source:

   jmp_buf jumper;

   int SomeFunction(int a, int b)
   {
      if (b == 0) // can't divide by 0
         longjmp(jumper, -3);
      return a / b;
   }

   void main(void)
   {
      if (setjmp(jumper) == 0)
      {
         int Result = SomeFunction(7, 0);
         // continue working with Result
      }
      else
         printf("an error occured\n");
   }

I'm currently going from C to Java and I'm having a hard time understanding why you'd use try/catch in the first place. With good error checking you should be fine, always always always use the values that are returned from functions, check the errono values, and validate any user input.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top