Error Handling in C
C has no try and catch. When something goes wrong (a file is missing, memory runs out, the user types "abc" instead of a number), C functions report it through their return value and a global error code called errno. Your program must check these and react; otherwise it carries on with bad data or crashes.
In this lesson you will learn the error-handling tools of C: return codes, errno, perror(), strerror(), exit status (EXIT_SUCCESS/EXIT_FAILURE), and how to check malloc and strtol the right way.
What You Will Learn
- How C functions signal errors.
- What errno is and when it is valid.
- How perror() and strerror() turn errno into a message.
- How to design your own functions to return error codes.
- How to use exit status, exit() and EXIT_FAILURE.
- How to safely convert text to numbers with strtol.
Error Handling in C Explained
Exam definition: Error handling in C is done by checking the return value of each function call. Many library functions, on failure, return a special value (such as NULL, EOF or -1) and set the global integer errno (declared in <errno.h>) to an error code such as ENOENT or ERANGE. perror(msg) prints msg and the error description to stderr; strerror(code) returns the description as a string. A program reports overall success or failure to the operating system through its exit status.
Memory trick: Calling a function is like ordering food. The return value is the waiter's thumbs up or thumbs down. If it's thumbs down, errno is the reason slip ("out of stock" = ENOENT), and perror/strerror read that slip aloud. Always look at the thumb before reading the slip.
How standard functions report failure
| Function | Failure return value | Sets errno? |
|---|---|---|
fopen | NULL | Yes (e.g. ENOENT, EACCES) |
malloc, calloc | NULL | Usually (ENOMEM) |
strtol, strtod | LONG_MAX / LONG_MIN / 0 | ERANGE when out of range |
scanf | Fewer items than expected, or EOF | No |
fclose, fputc | EOF | Yes |
atoi | 0 (can't tell error from "0") | No, so avoid it when errors matter |
Syntax of the Error Tools
#include <errno.h> /* errno, ENOENT, ERANGE, ... */
#include <stdio.h> /* perror */
#include <string.h> /* strerror */
#include <stdlib.h> /* exit, EXIT_SUCCESS, EXIT_FAILURE */
errno = 0; /* clear before a call that may set it */
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) /* 1. check the return value FIRST */
{
perror("data.txt"); /* 2a. "data.txt: No such file or directory" (stderr) */
printf("%s\n", strerror(errno)); /* 2b. same text as a string */
exit(EXIT_FAILURE); /* 3. stop with a failure status */
}
| errno name | Value* | Meaning |
|---|---|---|
ENOENT | 2 | No such file or directory |
ENOMEM | 12 | Cannot allocate memory |
EACCES | 13 | Permission denied |
EDOM | 33 | Math argument out of domain (e.g. sqrt(-1)) |
ERANGE | 34 | Result too large or too small |
*Values shown are the usual Linux/macOS numbers. Always use the names in code, never the numbers.
Example 1: Safe Number Conversion with strtol and Error Codes
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
enum parse_result { PARSE_OK, PARSE_EMPTY, PARSE_NOT_NUMBER, PARSE_OUT_OF_RANGE };
enum parse_result parse_int(const char *text, int *out)
{
char *end;
long value;
if (text[0] == '\0')
return PARSE_EMPTY;
errno = 0;
value = strtol(text, &end, 10);
if (*end != '\0')
return PARSE_NOT_NUMBER; /* extra characters like "12abc" */
if (errno == ERANGE || value > INT_MAX || value < INT_MIN)
return PARSE_OUT_OF_RANGE;
*out = (int)value;
return PARSE_OK;
}
int main(void)
{
const char *inputs[] = {"42", "-17", "12abc", "", "99999999999999999999"};
const char *messages[] = {"ok", "empty input", "not a number", "out of range"};
int i, n;
for (i = 0; i < 5; i++)
{
enum parse_result r = parse_int(inputs[i], &n);
if (r == PARSE_OK)
printf("\"%s\" -> %d\n", inputs[i], n);
else
printf("\"%s\" -> error: %s\n", inputs[i], messages[r]);
}
return 0;
}
Output
"42" -> 42 "-17" -> -17 "12abc" -> error: not a number "" -> error: empty input "99999999999999999999" -> error: out of range
Code Explanation
parse_intreturns an error code (an enum) and gives the result through a pointer. This is the standard C pattern: return value = success or failure; output parameter = the data.errno = 0;clears old errors. errno is only meaningful right after a call that failed, so we reset it first.strtol(text, &end, 10)converts the text and makesendpoint to the first character it couldn't use. If*endis not'\0', the text had junk like "abc".- For a huge number, strtol returns
LONG_MAXand setserrno = ERANGE. We also reject values that fit a long but not an int. atoi("12abc")would quietly return 12 andatoi("abc")would return 0, with no way to know something was wrong. That's why strtol is preferred.
How Error Handling Flows in a C Program
call a function
|
v
did it return the failure value (NULL, EOF, -1, ...)?
|-- no --> use the result, continue
|
`-- yes --> read errno immediately (other calls may overwrite it)
report: perror("context") or strerror(errno)
recover: use a default, ask again, free memory ...
or stop: return an error code / exit(EXIT_FAILURE)
- Exit status:
return 0;orexit(EXIT_SUCCESS)means success; a non-zero value orEXIT_FAILUREmeans failure. Scripts and other programs read this value (echo $?in Linux). perrorwrites to stderr, a separate output stream for errors, so error messages still show on screen even when normal output is redirected to a file.
Example 2: Handling a Missing File and Failed Allocation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int load_volume(const char *filename, int *volume)
{
FILE *fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Error: cannot open %s: %s\n", filename, strerror(errno));
return -1;
}
if (fscanf(fp, "%d", volume) != 1)
{
printf("Error: %s has no number\n", filename);
fclose(fp);
return -1;
}
fclose(fp);
return 0;
}
int main(void)
{
int volume;
int *scores;
if (load_volume("settings.cfg", &volume) != 0)
{
volume = 50; /* recover with a default */
printf("Using default volume %d\n", volume);
}
scores = malloc(5 * sizeof *scores);
if (scores == NULL) /* always check malloc */
{
printf("Error: out of memory\n");
return EXIT_FAILURE;
}
scores[0] = 91;
printf("First score: %d\n", scores[0]);
free(scores);
printf("Program finished with status %d\n", EXIT_SUCCESS);
return EXIT_SUCCESS;
}
Output
Error: cannot open settings.cfg: No such file or directory Using default volume 50 First score: 91 Program finished with status 0
- The file doesn't exist, so
fopenreturns NULL witherrno = ENOENT, andstrerrorturns it into "No such file or directory". - The program recovers: a missing settings file isn't fatal, so it uses a default value.
mallocis checked even though it rarely fails on a PC; on small devices it can.- Running out of memory is serious here, so that branch returns
EXIT_FAILURE.
Important Points to Remember
- C has no exceptions: check every return value that can signal failure.
- Read errno only after a failure, and right away; set
errno = 0before calls like strtol. perror(msg)→ stderr;strerror(errno)→ a string you can print anywhere.- Your own functions: return an error code, give results through pointers.
EXIT_SUCCESS(0) andEXIT_FAILURE(non-zero) report the program's result.- Prefer
strtoloveratoiwhen the input may be wrong.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
| Not checking fopen/malloc | Crash on NULL pointer use | if (p == NULL) { report; recover or exit; } |
| Checking errno without a failure | Old, unrelated error is reported | Check the return value first |
| Calling printf before reading errno | printf may change errno | Save it: int e = errno; |
| Using atoi on user input | "abc" silently becomes 0 | Use strtol with an end pointer |
exit(1) everywhere, even deep in a library function | Caller can't recover or clean up | Return an error code; let main decide |
Error Handling Practice Questions
- How are errors reported in C, since there are no exceptions?
- What is errno? Which header declares it?
- What is the difference between perror and strerror?
- Why is strtol better than atoi for user input?
- What do EXIT_SUCCESS and EXIT_FAILURE mean?
Show answers
- Through return values (NULL, EOF, -1, error codes) and the global errno, which the program must check.
- A global integer holding the code of the last error set by a failing library call;
<errno.h>. - perror prints a message plus the error description to stderr; strerror returns the description as a string for you to use.
- strtol reports where conversion stopped and sets ERANGE on overflow, so invalid or too-large input can be detected; atoi gives no error information.
- Exit status values from
<stdlib.h>telling the operating system the program succeeded (0) or failed (non-zero).
Coding Exercise
Write int safe_divide(int a, int b, int *result) that returns 0 on success and −1 if b is 0 (setting errno = EDOM). In main, divide 20 by 4 and 7 by 0, and for errors print the message with strerror(errno).
Show solution
#include <stdio.h>
#include <string.h>
#include <errno.h>
int safe_divide(int a, int b, int *result)
{
if (b == 0)
{
errno = EDOM;
return -1;
}
*result = a / b;
return 0;
}
int main(void)
{
int pairs[2][2] = {{20, 4}, {7, 0}};
int i, r;
for (i = 0; i < 2; i++)
{
if (safe_divide(pairs[i][0], pairs[i][1], &r) == 0)
printf("%d / %d = %d\n", pairs[i][0], pairs[i][1], r);
else
printf("%d / %d failed: %s\n", pairs[i][0], pairs[i][1], strerror(errno));
}
return 0;
}
20 / 4 = 5 7 / 0 failed: Numerical argument out of domain
The exact wording of the EDOM message can differ slightly between systems.
Quick Quiz: Error Handling in C (MCQ)
-
errno is declared in:
A) stdio.h B) errno.h C) error.h D) stdlib.h
-
perror prints to:
A) stdout B) stderr C) A file D) Nowhere
-
What does malloc return when it fails?
A) 0 bytes B) NULL C) -1 D) EOF
-
strtol sets errno to which value for an out-of-range number?
A) ENOENT B) EDOM C) ERANGE D) EACCES
-
Which value tells the OS the program failed?
A) EXIT_SUCCESS B) 0 C) EXIT_FAILURE D) NULL
Show answers
- B: errno.h.
- B: stderr.
- B: NULL.
- C: ERANGE.
- C: EXIT_FAILURE.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| C errors | Return values + errno (no exceptions) |
|---|---|
| errno | Global error code, <errno.h> |
| perror(msg) | msg + description to stderr |
| strerror(e) | Description as a string (string.h) |
| ENOENT / ERANGE | No such file / out of range |
| Exit status | EXIT_SUCCESS (0), EXIT_FAILURE |
| Safe conversion | strtol, not atoi |
Frequently asked questions
- How is error handling done in C?
- By checking return values and, after a failure, reading errno and reporting it with perror or strerror.
- When is errno valid?
- Only right after a function has failed; successful calls may leave old values in it.
- What is the exit status of a C program?
- The value returned by main or passed to exit: 0 / EXIT_SUCCESS for success, non-zero / EXIT_FAILURE for failure.
Remember
- Check the thumb (return value) before reading the slip (errno).
- Every fopen and malloc gets an if-check.
Next Topic
Next lesson: Undefined Behavior in C. You will learn what undefined behavior is and the common C mistakes that cause it.