Is there a better way to do C style error handling?

前端 未结 10 1910
时光说笑
时光说笑 2021-02-20 06:43

I\'m trying to learn C by writing a simple parser / compiler. So far its been a very enlightening experience, however coming from a strong background in C# I\'m having some pro

10条回答
  •  太阳男子
    2021-02-20 07:14

    Use setjmp.

    http://en.wikipedia.org/wiki/Setjmp.h

    http://aszt.inf.elte.hu/~gsd/halado_cpp/ch02s03.html

    http://www.di.unipi.it/~nids/docs/longjump_try_trow_catch.html

    #include 
    #include 
    
    jmp_buf x;
    
    void f()
    {
        longjmp(x,5); // throw 5;
    }
    
    int main()
    {
        // output of this program is 5.
    
        int i = 0;
    
        if ( (i = setjmp(x)) == 0 )// try{
        {
            f();
        } // } --> end of try{
        else // catch(i){
        {
            switch( i )
            {
            case  1:
            case  2:
            default: fprintf( stdout, "error code = %d\n", i); break;
            }
        } // } --> end of catch(i){
        return 0;
    }
    

    #include 
    #include 
    
    #define TRY do{ jmp_buf ex_buf__; if( !setjmp(ex_buf__) ){
    #define CATCH } else {
    #define ETRY } }while(0)
    #define THROW longjmp(ex_buf__, 1)
    
    int
    main(int argc, char** argv)
    {
       TRY
       {
          printf("In Try Statement\n");
          THROW;
          printf("I do not appear\n");
       }
       CATCH
       {
          printf("Got Exception!\n");
       }
       ETRY;
    
       return 0;
    }
    

提交回复
热议问题