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

前端 未结 10 1836
时光说笑
时光说笑 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:17

    A goto statement is the easiest and potentially cleanest way to implement exception style processing. Using a macro makes it easier to read if you include the comparison logic inside the macro args. If you organize the routines to perform normal (i.e. non-error) work and only use the goto on exceptions, it is fairly clean for reading. For example:

    /* Exception macro */
    #define TRY_EXIT(Cmd)   { if (!(Cmd)) {goto EXIT;} }
    
    /* My memory allocator */
    char * MyAlloc(int bytes)
    {
        char * pMem = NULL;
    
        /* Must have a size */
        TRY_EXIT( bytes > 0 );
    
        /* Allocation must succeed */
        pMem = (char *)malloc(bytes);
        TRY_EXIT( pMem != NULL );
    
        /* Initialize memory */
        TRY_EXIT( initializeMem(pMem, bytes) != -1 );
    
        /* Success */
        return (pMem);
    
    EXIT:
    
        /* Exception: Cleanup and fail */
        if (pMem != NULL)
            free(pMem);
    
        return (NULL);
    }
    

提交回复
热议问题