Error Handling with errno in C
C has no exceptions — library failures report through return values plus the errno integer (<errno.h>): functions return sentinel values (-1, NULL) and set errno to a code (ENOENT, EACCES, ERANGE) that perror() narrates ("open: No such file") and strerror() stringifies. Check immediately: any subsequent library call may overwrite errno.
The protocol is three steps — call, test the documented failure sentinel, then read errno before anything else runs. Some functions (strtol) need errno preset to 0 first to distinguish real errors from stale values.
Sentinel plus code
fopen returns NULL on failure and sets errno — the pointer says it failed, errno says why.
Read errno immediately
Another library call can reset it — capture or report errno before doing anything else.
perror narrates
perror("open") prints "open: No such file or directory" — your prefix plus the system's reason.
Preset for strtol
errno = 0; before strtol, then test ERANGE after — otherwise a stale error code misleads.
#include <stdio.h>#include <errno.h>#include <string.h> int main(void) { FILE *f = fopen("/no/such/file", "r"); if (!f) { printf("code %d: %s\n", errno, strerror(errno)); } return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.