C has no exceptions. Functions report failure through return values (NULL, -1, an error enum), the global errno, or output parameters. Callers must check them. A common pattern is a single cleanup path with goto so every resource is released on every error.
Remember
enum { OK = 0, ERR_DIV0 = -1 };
int divide(int a, int b, int *out) {
if (b == 0) return ERR_DIV0;
*out = a / b;
return OK;
}
Reference
Cheat Sheet
Keep these facts handy while you work with Error Handling in C.
Topic
Detail
Return codes
Zero for success, negative for error
errno
Set by many library functions
Cleanup
One exit label with goto
Exit status
return from main or exit(code)
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: errno and perror().
Example 1 — Return an error code instead of crashing
The result goes through a pointer; the return value signals success.
C
#include <stdio.h>
enum { OK = 0, ERR_DIV0 = -1 };
static int divide(int a, int b, int *out) {
if (b == 0) return ERR_DIV0;
*out = a / b;
return OK;
}
int main(void) {
int r;
if (divide(10, 0, &r) != OK) printf("error: division by zero\n");
if (divide(10, 2, &r) == OK) printf("result = %d\n", r);
return 0;
}
Output
error: division by zero
result = 5
How It Works
The function checks the divisor before dividing.
The caller checks the return code.
On success the quotient is written through out.
Edge Cases & Pitfalls
Check these before relying on Error Handling in real programs.
ignore
Ignoring return values
Unchecked failures turn into later crashes. Use __attribute__((warn_unused_result)) or review carefully.
mix
Mixing error styles
Pick a convention per project, such as 0 success and negative errors, and document it.
Remember
Key Takeaways
Check: every fallible call.
Convention: one style.
Cleanup: single exit.
One line: C has no exceptions.
Frequently Asked Questions
By returning status codes, setting errno, using output parameters, and checking those results at every call site.
On error, jump to a label near the end of the function that frees resources in reverse order, so cleanup code is written once.
Continue with "C errno and perror()" next. Read errno, print readable messages with perror and strerror. The C Advanced Concepts hub lists every topic in order.