ugh.book

(singke) #1

194 Programming


Exceptions are conditions that can arise when a function does not behave
as expected. Exceptions frequently occur when requesting system services
such as allocating memory or opening files. Since C provides no exception-
handling support, the programmer must add several lines of exception-han-
dling code for each service request.

For example, this is the way that all of the C textbooks say you are sup-
posed to use the malloc() memory allocation function:
struct bpt *another_function()
{
struct bpt *result;

result = malloc(sizeof(struct bpt));
if (result == 0) {
fprintf(stderr, “error: malloc: ???\n”);

/* recover gracefully from the error */
[...]
return 0;
}
/* Do something interesting */
[...]
return result;
}

The function another_function allocates a structure of type bpt and returns
a pointer to the new struct. The code fragment shown allocates memory for
the new struct. Since C provides no explicit exception-handling support,
the C programmer is forced to write exception handlers for each and every
system service request (this is the code in bold).

Or not. Many C programmers choose not to be bothered with such triviali-
ties and simply omit the exception-handling code. Their programs look like
this:
struct bpt *another_function()
{
struct bpt *result=malloc(sizeof(struct bpt));

/* Do something interesting */
return result;
}

It’s simpler, cleaner, and most of the time operating system service
requests don’t return errors, right? Thus programs ordinarily appear bug
Free download pdf