← The C Language Lesson 58 of 77 · 10 XP

Handling errors

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

C has no exceptions. Errors are reported through the return value, and the calling code is obliged to check it.

Common conventions:

  • the function returns 0 on success and non-zero (or -1) on error, and writes the result through a pointer;
  • the function returns a pointer or NULL;
  • the global variable errno (from <errno.h>) holds the code of the last system error, and perror and strerror(errno) turn it into text.
int parse_age(const char *s, int *out)
{
    char *end;
    long v = strtol(s, &end, 10);
    if (*s == '\0' || *end != '\0')
        return -1;            // not a number
    if (v < 0 || v > 150)
        return -2;            // out of range
    *out = (int)v;
    return 0;
}

A program tells the OS about success with the return code of main: return 0; or EXIT_SUCCESS, and on error — return 1; or EXIT_FAILURE. In bash you can see it in $?.

Error messages are written to stderr so that they don't mix with the useful output.

Task. Finish parse_age following the example from the theory. The program reads strings until the end of the input and for each one prints the age, error: not a number or error: out of range.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.