Try catch statements in C

前端 未结 13 1522
眼角桃花
眼角桃花 2020-11-27 10:06

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 tr

13条回答
  •  情书的邮戳
    2020-11-27 10:31

    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

提交回复
热议问题