Skip to content

Instantly share code, notes, and snippets.

@mcjohnalds
Created May 12, 2016 12:28
Show Gist options
  • Save mcjohnalds/b0302f80b0673870752955206c9a8ecc to your computer and use it in GitHub Desktop.
Save mcjohnalds/b0302f80b0673870752955206c9a8ecc to your computer and use it in GitHub Desktop.
How to report errors in C.

How to report errors in C

C doesn't support exceptions, but we can store error messages in structs. This document compares 3 different strategies of error reporting.

typedef enum {
    FILE_NOT_FOUND_ERROR,
    INVALID_FILE_FORMAT_ERROR,
    ...
} ErrorType;

typedef struct {
    ErrorType type;
    char* message;
} Error;

Strategy 1

int func1(Error* error);
No error checking: 1 line
int result = func1(NULL); // Here we just assume func1 will work
Full error checking: 6+ lines
Error* error;
int result = func1(error);
if (error) {
    ...
    free(error->message);
}

I find this one reads most naturally.

Strategy 2

Error* func2(int* result);
No error checking: 2 lines
int result;
func2(&result);
Full error checking: 6+ lines
int result;
Error* error = func2(&result);
if (error) {
    ...
    free(error->message);
}

This one's not very nice, I wouldn't use it.

Strategy 3

bool func3(int* result, Error* error);
No error checking: 2 lines
int result;
func3(&result, NULL);
Partial error checking: 4+ lines
int result;
if (!func3(&result, NULL)) {
    ... /* We care that func3 had an error, but we don't care what that error
         * is, and so we don't need to free anything
}
Full error checking: 6+ lines
int result;
Error* error;
if (!func3(&result, error)) {
    ...
    free(error->essage);
}

This one is the most complicated but also the most flexible. This is what GLib uses. If your already using GLib in your project, see https://developer.gnome.org/glib/2.42/glib-Error-Reporting.html.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment