Learn/C/9. Handling errors
Lesson 9 of 15
Sign in

C, lesson 9

Handling errors

C has no exceptions. When something goes wrong, a function tells its caller through its return value, and the caller is responsible for checking it. Nothing forces you to check, which is why unchecked errors are one of the most common bugs in C programs. The good news is that the patterns are simple and few.

Pattern 1: a special return value

Many library functions return a value that can't be a normal result when they fail:

  • scanf returns how many items it stored, or EOF.
  • fgets returns a null pointer at the end of input.
  • fopen returns a null pointer if the file can't be opened.
  • malloc returns a null pointer when memory runs out.

fprintf(stderr, ...) writes to standard error, a second output stream meant for problems. Keeping error messages off standard output means a program that pipes your output somewhere else still gets clean data.

2 exercises to try what you just read.

Exercise 1

Careful number reader

Press Ctrl Enter or Check to test your code.

Exercise 2

Bank account log

Press Ctrl Enter or Check to test your code.

Pattern 2: a status code

When the normal result could be any value, return a status and deliver the result some other way. An enum gives the status codes readable names:

The caller then uses a switch to react to each case. Mark functions whose result must not be ignored with the C23 attribute [[nodiscard]]; GCC then warns whenever someone calls the function and throws the result away.

Pattern 3: errno

Some library functions set the global variable errno (from <errno.h>) to a code that explains the failure, such as ERANGE for "result out of range". Two rules:

  1. Library functions set errno on failure but never reset it, so set errno = 0; yourself right before the call you want to check.
  2. Only look at errno after a call that actually reported a failure, or that documents it as the way to detect one.

perror("message") prints your message followed by a description of the current errno to standard error, and strerror(errno) gives you that description as a string.

Parsing numbers safely with strtol

atoi("12abc") quietly returns 12, and atoi("hello") returns 0, so you can't tell good input from bad. strtol (and strtoll for long long) reports exactly what happened:

strtol skips leading spaces, reads an optional sign and digits, and stores in end a pointer to the first character it did not use. If end still points at the start, nothing was converted. If *end is not the terminator, there was extra text after the number.

Exit codes

main's return value is the program's exit status. 0 (or EXIT_SUCCESS from <stdlib.h>) means success. Return EXIT_FAILURE when the program could not do its job, so scripts that run it can notice. From deep inside a program, exit(EXIT_FAILURE) ends it immediately.

Further reading

  • cppreference: errno
  • cppreference: strtol, strtoll
  • cppreference: perror
  • cppreference: Enumerations
  • cppreference: Attribute [[nodiscard]]

A sensor log arrives one value per line, but some lines are damaged. Read lines until the input ends. Remove the trailing newline, then use strtoll with base 10 on each line:

  • if the whole line is a valid integer (leading spaces allowed, nothing after the digits), print ok <value> and add it to a running sum
  • if strtoll reports ERANGE, print too big: <line>
  • otherwise print bad: <line>

After the last line, print sum: <sum>. Lines are at most 100 characters.

Write a function that validates a transaction and returns a status code from this enum:

The input starts with the opening balance (an integer). Each following line is a command, deposit <amount> or withdraw <amount>, until the input ends. For each command print:

SituationOutput
amount is 0 or negativeError: amount must be positive
withdrawal larger than the balanceError: insufficient funds
successful depositDeposited <amount>
successful withdrawalWithdrew <amount>
any other command wordError: unknown command <word>

Failed commands leave the balance unchanged. Finally print Balance: <balance>.

int age;
if (scanf("%d", &age) != 1) {
    fprintf(stderr, "Expected a number\n");
    return 1;
}
enum status { STATUS_OK, STATUS_EMPTY, STATUS_TOO_LONG };

enum status check_username(const char *name) {
    size_t len = strlen(name);
    if (len == 0) return STATUS_EMPTY;
    if (len > 16) return STATUS_TOO_LONG;
    return STATUS_OK;
}
[[nodiscard]] enum status save_game(int slot);
const char *text = "  42kg";
char *end;
errno = 0;
long value = strtol(text, &end, 10);   // base 10

if (end == text) {
    puts("no digits at all");
} else if (errno == ERANGE) {
    puts("number too large for long");
} else if (*end != '\0') {
    printf("number %ld followed by junk: %s\n", value, end);  // 42, "kg"
}
Input:
12
-7
3kg
hello
Output:
ok 12
ok -7
bad: 3kg
bad: hello
sum: 5
enum result { RESULT_OK, RESULT_BAD_AMOUNT, RESULT_NO_FUNDS };
Input:
100
withdraw 30
withdraw 500
deposit -5
deposit 20
Output:
Withdrew 30
Error: insufficient funds
Error: amount must be positive
Deposited 20
Balance: 90