Error Handling
Lesson 18 of 20C has no exceptions — return codes, errno and perror are your only safety net, so learn to use all three.
Errors travel through returns
C has no exceptions and no crash guards — errors travel back through return values, errno and stderr.
Return codes
Functions signal trouble with their return value — 0 usually means success.
errno remembers
Library calls store a small code in errno describing exactly what went wrong.
perror explains
perror("open") prints your word plus the system's own explanation of errno.
stderr for errors
Error messages belong on stderr — the diagnostics channel, separate from normal output.
The fopen safety pattern
The most common error check in C: try to open, test for NULL, react.
Report a failure, do not crash
Press play — divide() refuses to divide by zero and reports it with a code instead of crashing.
1#include <stdio.h>23int divide(int a, int b, int *out) {4if (b == 0) {5return -1;6}7*out = a / b;8return 0;9}1011int main(void) {12int result = 0;13int status = divide(9, 0, &result);14if (status != 0) {15fprintf(stderr, "Error: %d\n", status);16return 1;17}18printf("9 / 0 = %d\n", result);19return 0;20}
The preprocessor pastes in stdio.h — printf and fprintf come from there.
Match the error toolkit
Click a tool, then click its job to lock the pair.
Predict the output
The file does not exist in this run — which line prints?
1#include <stdio.h>23int main(void) {4FILE *f = fopen("missing.txt", "r");5if (f == NULL) {6printf("Could not open\n");7return 1;8}9printf("Opened fine\n");10return 0;11}
Hint: No file called missing.txt exists — fopen fails and returns NULL, so the guard fires.
Key takeaways
C has no exceptions — errors travel through return values.
A 0 return usually means success; anything else means look closer.
errno plus perror turn system failures into human sentences.
Send errors to stderr so they never pollute program output.
Check every risky call before using its result — fopen, malloc and friends have no guardrails.