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);
10  /*error handler*/
11  void handle_error(void);
12 
13  int main(int argc, char *argv[])
14  {
15    int a, b, c;
16    int user = 10;
17    printf ("Give two numbers for division : ");
18    scanf("%d %d", &a, &b);
19    if(setjmp(jb) == 0)
20    {
21      c = division(a, b);
22      printf ("%d / %d = %d", a, b, c);
23      return 0;
24    }
25    else
26    {
27      handle_error();
28      return -1;
29    }
30    
31  }
32 
33  int division(int a, int b)
34  {
35    int error_flag = 0;
36    if(== 0)
37    {
38      error_flag = 1;
39    }
40    if(error_flag == 1)
41    {
42      longjmp(jb, 1);
43    }
44    else
45    {
46      return (/ b);
47    }
48  }
49 
50  void handle_error(void)
51  {
52    printf("Div by zero error !");
53  }

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

 Vote 0

Similar topics related to this section

strdup, strtok, macro definition, C exception handling, setjmp and longjmp, trace a memory leak, detect memory corruption,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan