Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C : How do you simulate an 'exception'?

I come from a C# background, but I'm learning C at the moment. In C#, when one wants to signal that an error has occurred, you throw an exception. But what do you do in C?

Say for example you have a stack with push and pop functions. What is the best way to signal that the stack is empty during a pop ? What do you return from that function?

double pop(void)
{
    if(sp > 0)
        return val[--sp];
    else {
        printf("error: stack empty\n");
        return 0.0;
    }
}

K&R's example from page 77 (code above) returns a 0.0. But what if the user pushed a 0.0 earlier on the stack, how do you know whether the stack is empty or whether a correct value was returned?

like image 407
Andreas Grech Avatar asked Aug 02 '09 18:08

Andreas Grech


People also ask

How are exceptions handled in C?

The C programming language does not support exception handling nor error handling. It is an additional feature offered by C. In spite of the absence of this feature, there are certain ways to implement error handling in C. Generally, in case of an error, most of the functions either return a null value or -1.

Is there a try except in C?

The try-except statement is a Microsoft extension to the C language that enables applications to gain control of a program when events that normally terminate execution occur. Such events are called exceptions, and the mechanism that deals with exceptions is called structured exception handling.

Can you throw exceptions in C?

C doesn't support exceptions. You can try compiling your C code as C++ with Visual Studio or G++ and see if it'll compile as-is. Most C applications will compile as C++ without major changes, and you can then use the try... catch syntax.


1 Answers

Exception-like behavior in C is accomplished via setjmp/longjmp. However, what you really want here is an error code. If all values are potentially returnable, then you may want to take in an out-parameter as a pointer, and use that to return the value, like so:

int pop(double* outval)
{
        if(outval == 0) return -1;
        if(sp > 0)
                *outval = val[--sp];
        else {
                printf("error: stack empty\n");
                return -1;
        }
        return 0;
}

Not ideal, obviously, but such are the limitations of C.

Also, if you go this road, you may want to define symbolic constants for your error codes (or use some of the standard ones), so that a user can distinguish between "stack empty" and "you gave me a null pointer, dumbass".

like image 128
Tyler McHenry Avatar answered Oct 12 '22 09:10

Tyler McHenry