Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I throw (and possibly catch) an exception in plain C (GCC)? [duplicate]

Tags:

c

I was thinking today about the try/catch blocks existent in another languages. Googled for a while this but with no result. From what I know, there is not such a thing as try/catch in C. However, is there a way to "simulate" them?
Sure, there is assert and other tricks but nothing like try/catch, that also catch the raised exception. Thank you

like image 453
Andrew Avatar asked Nov 24 '22 00:11

Andrew


1 Answers

C itself doesn't support exceptions but you can simulate them to a degree with setjmp and longjmp calls.

static jmp_buf s_jumpBuffer;

void Example() { 
  if (setjmp(s_jumpBuffer)) {
    // The longjmp was executed and returned control here
    printf("Exception happened here\n");
  } else {
    // Normal code execution starts here
    Test();
  }
}

void Test() {
  // Rough equivalent of `throw`
  longjmp(s_jumpBuffer, 42);
}

This website has a nice tutorial on how to simulate exceptions with setjmp and longjmp

  • http://www.di.unipi.it/~nids/docs/longjump_try_trow_catch.html
like image 59
JaredPar Avatar answered Jan 25 '23 23:01

JaredPar