c

Try catch statements in 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


Solution

  • 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