try-catch vs setjmp-longjmp

ANSI C does not support try-catch block like C++. Alternatively it supports setjmp-longjmp which is similar to a try-catch block.

setjmp-longjmp uses variable type jmp_buf to store return context of setjmp to be used by longjmp at error condition. setjmp saves the CPU context in the buffer and returns 0. Afterwards if some error occurs, program calls logjmp which restores the last saved context. Thus the CPU again jumps to previous context of setjmp and now setjmp returns a non-zero value and it goes to the exception path. Following example will illustrate this concept.

setjmp

int setjmp(jmp_buf context);
Saves the environment into the variable 'context'. If a non-zero value is returned, then this indicates that the point in the source code was reached by a longjmp. Otherwise zero is returned indicating the context has been saved in 'context'.

longjmp

void longjmp(jmp_buf context, int value);
Causes the 'context' to be restored from a setjmp call where the environment variable had been saved. It causes the execution to jump to the setjmp location as if setjmp had returned the value of the variable 'value'. The variable 'value' cannot be zero. However, if zero is passed, then it is replaced by 1. If the function where setjmp was called has terminated, then the results are undefined.

setjmp-longjmp - source code

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

/*buffer to hold context of jump*/
jmp_buf jb;

/*div a/b throws error*/
int division(int a, int b);

/*error handler*/
void handle_error(void);

int main(int argc, char *argv[])
{
  int a, b, c;
  int user = 10;
  printf ("Give two numbers for division : ");
  scanf("%d %d", &a, &b);
  if(setjmp(jb) == 0)
  {
    c = division(a, b);
    printf ("%d / %d = %d", a, b, c);
    return 0;
  }
  else
  {
    handle_error();
    return -1;
  }
  
}

int division(int a, int b)
{
  int error_flag = 0;
  if(== 0)
  {
    error_flag = 1;
  }
  if(error_flag == 1)
  {
    longjmp(jb, 1);
  }
  else
  {
    return (/ b);
  }
}

void handle_error(void)
{
  printf("Div by zero error !");
}

About our authors: Team EQA

You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.

#