Error Handling Conventions
Prerequisites: Debugging with GDB and Valgrind
C has no exceptions — errors are reported through a function's
return value (commonly 0/non-0, or a sentinel like NULL or
-1) and the global errno variable for standard library calls.
#include <errno.h>
#include <string.h>
FILE *file = fopen("missing.txt", "r");
if (file == NULL) {
printf("Error: %s\n", strerror(errno));
return 1;
}
This means every call that can fail must be checked explicitly at the call site — there's no automatic mechanism that halts execution or unwinds the stack the way an uncaught exception would in Java or Python.
Common mistakes
- Ignoring a function's return value "because it usually works" — in C, that's the only place many errors are ever reported at all.