Learn C
#include "stdlib/errno.h"

Error Handling with errno in C

#concept

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.

#how it works
1

Sentinel plus code

fopen returns NULL on failure and sets errno — the pointer says it failed, errno says why.

2

Read errno immediately

Another library call can reset it — capture or report errno before doing anything else.

3

perror narrates

perror("open") prints "open: No such file or directory" — your prefix plus the system's reason.

4

Preset for strtol

errno = 0; before strtol, then test ERANGE after — otherwise a stale error code misleads.

#example
#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;
}
Output
code 2: No such file or directory
1Opening a nonexistent path fails, returning NULL and setting errno to ENOENT (2).
2The check reads errno immediately — nothing ran between failure and report.
3strerror translates code 2 to its message — programmatic code plus human text.
#use cases
Explaining every library failure with perror/strerror context
Distinguishing error kinds (missing vs denied) by errno value
Presetting errno = 0 around strtol-family calls
Never letting another call clobber errno before inspection

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.